Parcel-delivery app~15 min2s · 256 MBtarget O(total log n) time, O(n) spaceclassic twin: lc-2335heaps
A parcel-delivery hub sends parcels to delivery zones. Each minute, the hub can load one parcel into each of two vans, and the two vans must go to different zones. It can also load a single van.
Your team lead asks: "In how many minutes can we clear every zone?" You are given the number of parcels waiting for each zone.
Write min_minutes(waiting).
waiting[i] is the number of parcels waiting for zone i. A zone can have no parcels.0 when no parcel is waiting.Input: waiting = [1, 4, 2]
Output: 4Each minute, load the two fullest zones. The table shows the parcels waiting for each zone, from the fullest down, before the minute.
| Minute | Parcels waiting before | Zones loaded (parcels before) | Waiting after |
|---|---|---|---|
| 1 | 4, 2, 1 | 4 and 2 | 3, 1, 1 |
| 2 | 3, 1, 1 | 3 and 1 | 2, 0, 1 |
| 3 | 2, 1, 0 | 2 and 1 | 1, 0, 0 |
| 4 | 1, 0, 0 | 1 | 0, 0, 0 |
Input: waiting = [5, 0, 0]
Output: 5Only one zone has parcels, so each minute loads one van.
Input: waiting = [3, 3, 3, 3]
Output: 6There are 12 parcels, and two go in every minute.
1 ≤ length of waiting ≤ 5,0000 ≤ waiting[i] ≤ 100With 5,000 zones of 100 parcels each, the hub has 500,000 parcels and needs 250,000 minutes. A first attempt that sorts all 5,000 zones again each minute does about 61,000 comparisons a minute, which is about 15 billion in all.
A heap gives the fullest zone in one step and takes about 12 steps to put one back. That is about 12 million steps for the whole input.