Bank app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-901monotonic-stack · stacks
A savings app shows the daily closing price of an investment fund. Next to each day it shows the span of that day. The span is the number of days in a row, counting back from that day and including it, with a price at or below that day's price.
The span stops at the first earlier day with a higher price. The app computes each span when the day's price arrives, using only earlier days. A fund can have up to 100,000 days.
Write price_spans(prices).
prices is a list of whole numbers, one for each day, oldest day first.i, count the days j from i going back to day 0, stopping before the first day whose price is higher than prices[i]. Day i itself counts, so the span is at least 1.Input: prices = [31, 27, 25, 29, 22, 28, 33, 33]
Output: [1, 1, 1, 3, 1, 2, 7, 8]Read the days in order. A stack holds the days whose price is still higher than every day after them. A new day pops the days at or below its price, and its span runs back to the day under the new top.
| Day | Price | Days popped | Stack after (days) | Span |
|---|---|---|---|---|
| 0 | 31 | none | 0 | 1 (stack empty, back to day 0) |
| 1 | 27 | none | 0, 1 | 1 (day 0 is higher) |
| 2 | 25 | none | 0, 1, 2 | 1 |
| 3 | 29 | days 2, 1 | 0, 3 | 3 (days 1, 2, 3) |
| 4 | 22 | none | 0, 3, 4 | 1 |
| 5 | 28 | day 4 | 0, 3, 5 | 2 (days 4, 5) |
| 6 | 33 | days 5, 3, 0 | 6 | 7 (stack empty, back to day 0) |
| 7 | 33 | day 6 | 7 | 8 (the equal price on day 6 counts) |
The output is [1, 1, 1, 3, 1, 2, 7, 8].
Input: prices = [10, 20, 30]
Output: [1, 2, 3]Each day is at least as high as every day before it, so each span reaches back to day 0 and equals the number of days so far.
Input: prices = [30, 20, 10]
Output: [1, 1, 1]Each day is lower than the day before it, which ends the span at once. Every span is 1.
1 ≤ number of days ≤ 10^51 ≤ each price ≤ 10^6A plan that walks back from every day costs up to n^2 / 2 steps: 5 × 10^9 when the prices rise all the way. That is too slow.
So the work must be close to n steps in all. Each day should be handled a constant number of times, even though its span can reach back to day 0.