Online store~25 min2s · 256 MBtarget O(n log n) time, O(n) spaceintervals · sorting
An online shop holds units of a product for customers while they check out. Each reservation takes some units from the stock for a period of seconds, and returns them when it ends. A shop with a flash sale can accept more reservations than it has units.
The operations team wants to know for how many seconds of the day the units reserved were more than the stock.
Write oversold_seconds(starts, ends, units, stock).
i holds units[i] units during the seconds from starts[i] up to, but not including, ends[i]. Always starts[i] < ends[i].t has returned its units by second t, so it does not overlap one that starts at t.stock.Input: starts = [0, 2, 4, 5], ends = [6, 5, 8, 9], units = [3, 2, 4, 1], stock = 5
Output: 2The trace sweeps through the start and end times in order, and adds the time spent while the reserved units were over the stock.
| Time | Change | Units reserved after | Seconds over stock since the last event | Total so far |
|---|---|---|---|---|
| 0 | +3 | 3 | 0 | 0 |
| 2 | +2 | 5 | 0 | 0 |
| 4 | +4 | 9 | 0 | 0 |
| 5 | -2 | 7 | 1 | 1 |
| 5 | +1 | 8 | 0 | 1 |
| 6 | -3 | 5 | 1 | 2 |
| 8 | -4 | 1 | 0 | 2 |
| 9 | -1 | 0 | 0 | 2 |
From second 4 to second 6, the reservations hold more than 5 units, so those 2 seconds are oversold. Before second 4 and after second 6, the total is at most 5. The output is 2.
Input: starts = [0], ends = [10], units = [1], stock = 0
Output: 10The stock is 0, so even one reserved unit is too many. All 10 seconds are oversold.
Input: starts = [0, 5], ends = [5, 10], units = [3, 3], stock = 3
Output: 0The first reservation ends at second 5, when the second one starts. They never overlap, and each holds 3 units, which is not over the stock of 3. The output is 0.
1 ≤ starts.length ≤ 100,000; ends and units have the same length0 ≤ starts[i] < ends[i] ≤ 86,400 (seconds in a day)1 ≤ units[i] ≤ 1,0000 ≤ stock ≤ 100,000,000 (units)Adding up the reservations that cover each second of the day costs up to 86,400 × 10^5 = 8.6 × 10^9 steps. The total only changes when a reservation starts or ends, so sorting the 2 × n change points and sweeping through them costs about 2 × n × log n steps.