Online store~30 min2s · 256 MBtarget O(n) time, O(n) spacemonotonic-stack
An online shop tracks the daily price of a product. A price is a bargain on its day, and it stays a bargain as long as no day around it has a lower price. The shop sends a price alert that says how long the bargain lasts, looking both back and forward.
For every day, the team wants the longest run of consecutive days that holds it. No price in the run may be lower than that day's price.
Write bargain_stretch(prices).
prices[i] is the price in units on day i.i, find the longest run of consecutive days that includes day i, and has no price lower than prices[i]. Days with an equal price may be in the run.Input: prices = [4, 2, 3, 5, 2, 6]
Output: [1, 6, 2, 1, 6, 1]The trace gives, for each day, the closest lower price on each side. Equal prices do not count as lower.
| Day | Price | Closest earlier day with a lower price | Closest later day with a lower price | Stretch |
|---|---|---|---|---|
| 0 | 4 | none | 1 | 1 |
| 1 | 2 | none | none | 6 |
| 2 | 3 | 1 | 4 | 2 |
| 3 | 5 | 2 | 4 | 1 |
| 4 | 2 | none | none | 6 |
| 5 | 6 | 4 | none | 1 |
Days 1 and 4 both have price 2, and no price is lower, so each has a stretch of the whole 6 days. Day 0 has price 4, and its run stops before day 1, whose price is lower.
Input: prices = [5]
Output: [1]One day: the run holds only that day, so the output is 1.
Input: prices = [1, 2, 3, 4]
Output: [4, 3, 2, 1]Prices rise every day. Day 0 is the lowest, so its run is all 4 days. Day 3 has the highest price, and every earlier day is lower, so its run is only itself.
1 ≤ prices.length ≤ 100,0001 ≤ prices[i] ≤ 10,000,000 (units)Expanding left and right from each day costs up to n × n / 2 steps when prices rise or fall steadily, about 5 × 10^9. A stack that keeps the prices in rising order finds the closest lower price on each side for all days in one pass. Each day enters and leaves the stack once.