Problem 390
Stock Span
Medium · 20 pts · Array, Stack, Monotonic Stack
Problem
The span of a stock's price on a given day is the number of consecutive days, ending with that day and going backwards, on which the price was less than or equal to that day's price. The span is always at least 1, because it includes the day itself. Given the daily prices, print the span for every day. A stack of previous higher prices makes this O(N) overall.
Input
First line: N. Second line: N daily prices.
Output
Print N spans, separated by spaces.
Constraints
1 <= N <= 100000; 1 <= price <= 100000
Example input
7 100 80 60 70 60 75 85
Example output
1 1 1 2 1 4 6
Explanation
For prices 100 80 60 70 60 75 85, the price 75 on day 6 is at least the prices of days 3, 4 and 5 (60, 70, 60) but less than 80 on day 2, so its span is 4. The full answer is 1 1 1 2 1 4 6.