Parcel-delivery app~25 min2s · 256 MBtarget O(n log S) time, O(1) spaceclassic twin: lc-1011, lc-410binary-search-answer · greedy
A parcel-delivery app moves parcels from a hub to a depot on a conveyor line. The parcels must leave in the order they arrive. Each day, one truck takes the next parcels in line, up to its weight capacity, and it may not leave a parcel behind that is in the middle.
All parcels must reach the depot within days days. What is the smallest truck capacity that makes this possible?
Write ship_capacity(weights, days).
weights[i] is the weight of parcel i, in the order they arrive.days days.Input: weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], days = 5
Output: 15The capacity is at least the heaviest parcel, 10, or that parcel could never ship. It is at most the total, 55, which ships everything in one day. Search the window [lo, hi), where hi always works. To check a capacity, load the parcels in order and start a new day whenever the next parcel does not fit.
| Step | lo | hi | mid | days needed at mid | Decision |
|---|---|---|---|---|---|
| 1 | 10 | 55 | 32 | 2 | 2 <= 5, so hi = 32 |
| 2 | 10 | 32 | 21 | 3 | 3 <= 5, so hi = 21 |
| 3 | 10 | 21 | 15 | 5 | 5 <= 5, so hi = 15 |
| 4 | 10 | 15 | 12 | 6 | 6 > 5, so lo = 13 |
| 5 | 13 | 15 | 14 | 6 | 6 > 5, so lo = 15 |
| end | 15 | 15 | the smallest capacity is 15 |
At capacity 15 the days are 1+2+3+4+5, 6+7, 8, 9 and 10.
Input: weights = [7], days = 1
Output: 7One parcel needs a truck that carries at least its weight, so the answer is 7, where the lower and upper ends of the window are equal.
Input: weights = [5, 5, 5, 5], days = 4
Output: 5With four days for four parcels, each parcel gets its own day. The capacity only has to cover the heaviest parcel, so the answer is 5, the lower end of the window.
1 ≤ weights.length ≤ 100,0001 ≤ weights[i] ≤ 1,000,000 (kilograms)1 ≤ days ≤ 100,000Trying every capacity from the heaviest parcel upwards, with a pass over the parcels each time, costs about n × (the answer) steps. The answer can be around 10^9, so that is far beyond 10^10. One pass costs n steps, and a binary search over the range up to the total weight needs about 37 passes, so about 4 × 10^6 steps.