</>CodexBash
Back to problems
Not started

How long this price has been the best

Medium
2000 ms limit256 MB memoryStacks and queuesArrays

Stuck?

Show a hint

The span ends at the most recent strictly higher price. Keep a stack of days that could still block a later day, and drop any that today outranks.

A share price is quoted once a day. The span on a given day is the number of consecutive days ending that day, today included, on which the price was less than or equal to today's price.

Report the span for every day.

Worked example#

For [100, 80, 60, 70, 60, 75, 85]:

daypricedays counted backspan
0100itself only1
180itself only, 100 is higher1
260itself only, 80 is higher1
37070 and 602
460itself only1
57575, 60, 70, 604
68585, 75, 60, 70, 60, 806

So the answer is [1, 1, 1, 2, 1, 4, 6].

The idea#

The span stops at the most recent day with a strictly higher price. Nothing before that day can be counted, because that day blocks the run. So the real question for each day is: where is the previous higher price?

Counting backwards day by day is a nested loop. Instead keep a stack of days whose prices are still higher than everything after them. When today arrives, pop every day priced at or below today, because none of them can ever block a later day again: today is higher and stands in front of them.

Whatever is left on top is the previous higher day, and the span is the distance to it. If the stack empties, no day has been higher, so the span reaches back to the very first day.

Each day is pushed once and popped once, so this is one pass however the prices move.

Constraints#

  • 1 <= n <= 100000
  • 1 <= prices[i] <= 1000000

Input

prices is a count then that many integers.

Output

A count is not printed. Print the spans, separated by spaces.

Examples

Input

7
100 80 60 70 60 75 85

Output

1 1 1 2 1 4 6

Day 6 at 85 reaches back past everything except the opening 100.

Input

4
10 4 5 90

Output

1 1 2 4

90 beats every earlier price, so its span is the whole run.

Input

3
5 5 5

Output

1 2 3

Equal prices still count, because the rule is less than or equal.

Something wrong with this problem? Report an issue

Ready to try it

Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.

Free, and it stays free. No card.