Online store~35 min2s · 256 MBtarget O(n + stock) time, O(n) spacequeues
An online shop runs a flash sale of a limited stock. Customers join a queue when they arrive. To keep the sale fair, the shop sells one unit at a time. The customer at the front buys one unit, and goes to the back of the queue if they want more.
The shop sells one unit each second while there is someone in the queue and stock left. The team wants to know when each customer got their last unit, and who left empty-handed.
Write finish_times(stock, arrivals, wants).
stock units. Customer i arrives at second arrivals[i] and wants wants[i] units. The arrival times never go down.-1 if they never got all of them.Input: stock = 7, arrivals = [0, 0, 2, 5], wants = [3, 1, 2, 2]
Output: [4, 1, 5, -1]The trace shows the queue at each second in which a unit is sold.
| Second | Queue before the sale | Buys | Still wants | Stock left | Then |
|---|---|---|---|---|---|
| 0 | 0, 1 | 0 | 2 | 6 | back of the queue |
| 1 | 1, 0 | 1 | 0 | 5 | finished |
| 2 | 0, 2 | 0 | 1 | 4 | back of the queue |
| 3 | 2, 0 | 2 | 1 | 3 | back of the queue |
| 4 | 0, 2 | 0 | 0 | 2 | finished |
| 5 | 2, 3 | 2 | 0 | 1 | finished |
| 6 | 3 | 3 | 1 | 0 | back of the queue |
The customers 0 and 1 arrive first, and customer 2 joins at second 2, and customer 3 at second 5. The seventh unit goes to customer 3 at second 6, and customer 3 still wants one more, so the stock runs out. The output is [4, 1, 5, -1].
Input: stock = 3, arrivals = [0, 10], wants = [1, 2]
Output: [0, 11]Customer 0 buys at second 0 and finishes. The shop is idle from second 1 to 9. Customer 1 arrives at second 10, and buys at seconds 10 and 11. The output is [0, 11].
Input: stock = 2, arrivals = [0, 0], wants = [2, 2]
Output: [-1, -1]The customers take turns, one unit each. The stock of 2 runs out after each has bought one unit, so neither gets all they want. The output is [-1, -1].
1 ≤ stock ≤ 1,000,000 (units)1 ≤ arrivals.length ≤ 100,000; 0 ≤ arrivals[i] ≤ 2,678,400 (seconds), never going down; wants has the same length1 ≤ wants[i] ≤ 1,000 (units)The shop sells at most stock units, one for each second it is busy, so the simulation has at most 10^6 sales. The idle gaps between arrivals can be long, up to 2.7 million seconds, so the loop must jump over them instead of ticking through every second.