Ride-hailing app~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-1732traversal · prefix-sums
A ride-hailing app keeps a pickup queue at a busy station. During the hour, riders join the queue and leave it, in groups. Each group is one event.
Your team lead says: "Tell me how long the queue got at its longest, and when that first happened, so we can send drivers earlier."
The queue never goes below 0: a group never leaves in larger numbers than are waiting.
Write peak_queue(start, changes).
start is the number of riders in the queue before the first event.changes[i] is the change at event i: positive when riders join, negative when riders leave.k events the queue length is start plus changes[0] + ... + changes[k - 1]. After 0 events it is start.[peak, when]: the largest queue length, and the smallest number of events after which that length occurs.Input: start = 3, changes = [2, -4, 5, 1, -2]
Output: [7, 4]The length after each event is the length before it plus the change.
| Events applied | Change | Queue length |
|---|---|---|
| 0 | - | 3 |
| 1 | 2 | 5 |
| 2 | -4 | 1 |
| 3 | 5 | 6 |
| 4 | 1 | 7 |
| 5 | -2 | 5 |
The peak is 7, first reached after 4 events.
Input: start = 0, changes = [0]
Output: [0, 0]A queue that never changes peaks at its start, after 0 events.
Input: start = 5, changes = [-5, 5]
Output: [5, 0]The length 5 at the start comes first, so when is 0.
0 ≤ start ≤ 100,000 (riders waiting at the start)1 ≤ changes.length ≤ 100,000 (events)-100,000 ≤ changes[i] ≤ 100,000 (riders joining or leaving)Adding up all the changes again after every event makes about 5,000,050,000 additions at 100,000 events. One running length makes 100,000. The length can reach 100,000 + 100,000 × 100,000, about 10^10, which is above 2,147,483,647, so it needs 64 bits.