Parcel-delivery app~30 min2s · 256 MBtarget O(n log n) time, O(n) spacegreedy · heaps
A delivery app collects orders from a restaurant district. Each order is ready for pickup at some minute, and the courier must collect it by a last pickup minute, or it is cancelled. A courier trip leaves at one moment and carries a bag that holds at most a few orders.
Operations wants the fewest trips that collect every order inside its window. A trip may leave at any whole minute.
Write min_trips(ready, latest, capacity).
i can be collected at any whole minute t with ready[i] <= t <= latest[i]. The orders are not sorted.t and collects at most capacity of the orders whose window contains t.Input: ready = [0, 1, 2, 6, 7, 10], latest = [4, 3, 8, 9, 12, 10], capacity = 2
Output: 3The trace keeps a heap of the last pickup times of the orders that are ready and still waiting. A trip leaves at the smallest of them.
| Trip | Waiting orders (last pickup times) | Leaves at | Takes | Left waiting |
|---|---|---|---|---|
| 1 | 3, 4, 8 | 3 | 3, 4 | 8 |
| 2 | 8, 9, 12 | 8 | 8, 9 | 12 |
| 3 | 10, 12 | 10 | 10, 12 | none |
Three trips are enough, so the output is 3. Before trip 2, the orders ready at minutes 6 and 7 have joined the heap, because they were ready by minute 8.
Input: ready = [5, 5, 5], latest = [5, 5, 5], capacity = 3
Output: 1All three orders are ready and due at minute 5, and the bag holds three.
Input: ready = [0, 10], latest = [1, 12], capacity = 5
Output: 2The windows [0, 1] and [10, 12] share no minute, so no trip can serve both.
1 ≤ ready.length ≤ 100,000 (orders); latest has the same length0 ≤ ready[i] ≤ latest[i] ≤ 1,000,000,000 (minutes)1 ≤ capacity ≤ 1,000 (orders in a bag)Trying every set of orders for every trip is exponential, and trying every departure minute is impossible with minutes up to 10^9. At 100,000 orders you want a rule that decides the next trip at once, with a heap for the urgent orders: about n log n steps.