Online store~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1475monotonic-stack · stacks
An online store shows the items of a collection in a row, each with a price in minor units. A step-down offer gives a discount on every item. The discount is the price of the first item after it in the row that costs the same or less.
If no later item costs the same or less, the item has no discount. The page shows the final price of every item. A collection can hold up to 100,000 items.
Write final_prices(prices).
prices is a list of whole numbers, one for each item, in the order of the row.i, find the first later item j (with j > i) whose price is the same as or lower than prices[i]. The discount is prices[j]. If there is no such item, the discount is 0.prices[i] minus its discount, in order.Input: prices = [900, 450, 620, 450, 700, 300]
Output: [450, 0, 170, 150, 400, 300]Read the items from left to right. A stack holds the items still waiting for a price that is the same or lower. A new price is the markdown of every waiting item that costs at least as much.
| Item read | Price | Items popped (final price) | Waiting stack after (items) |
|---|---|---|---|
| 0 | 900 | none | 0 |
| 1 | 450 | item 0: 900 - 450 = 450 | 1 |
| 2 | 620 | none | 1, 2 |
| 3 | 450 | item 2: 620 - 450 = 170; item 1: 450 - 450 = 0 | 3 |
| 4 | 700 | none | 3, 4 |
| 5 | 300 | item 4: 700 - 300 = 400; item 3: 450 - 300 = 150 | 5 |
Item 5 stays on the stack, so it keeps its full price of 300. The final prices are [450, 0, 170, 150, 400, 300].
Input: prices = [100, 200, 300]
Output: [100, 200, 300]Every price is higher than the one before it, so nobody finds a price that is the same or lower. Every item keeps its full price.
Input: prices = [500, 500, 500]
Output: [0, 0, 500]Equal counts. Item 0 is marked down by item 1, and item 1 by item 2. Item 2 has nothing after it.
1 ≤ number of items ≤ 10^51 ≤ each price ≤ 10^7A plan that scans to the right from every item 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 item should be handled a constant number of times, even though its markdown can sit far to its right.