Online Stock Span
Practice this coding question on Coding Gurukul.
Problem statement
A trading simulator receives one closing price each day. Its display shows how long the current price has dominated the most recent uninterrupted run of prices. The display must update as each new price arrives, using only that day and earlier days. Your task For each price, compute the largest number of consecutive days ending today whose prices are all less than or equal to today’s price. Include today itself. Stop the backward run at the first strictly higher earlier price; do not skip that day to include older prices. Equal prices extend the span. Process the observations in arrival order with amortized O(1) time per observation, using a stack of unresolved prices or aggregated spans. Print the span for every day rather than only the last one. Worked example For prices [40, 30, 30, 35, 50], the spans are 1, 1, 2, 3 and 5. The fourth price covers both preceding 30s but stops before 40. The final price covers the entire history.
Input format
First line: n. Second line: n prices in arrival order.
Output format
Print n space-separated spans.
Constraints
1 <= n <= 10000; 1 <= price <= 100000.
Sample input
5 40 30 30 35 50
Sample output
1 1 2 3 5
Sign in to run or submit a solution in C++, Java or Python.