Capacity To Ship Packages Within D Days
Difficulty: Medium · Pattern: Binary Search · LeetCode #1011
Packages with weights must be shipped in order within days days. Each day, packages are loaded in order up to the ship's capacity. Return the minimum capacity that ships everything in time.
Examples
text
weights = [1,2,3,4,5,6,7,8,9,10], days = 5 → 15
weights = [3,2,2,4,1,4], days = 3 → 6
weights = [1,2,3,1,1], days = 4 → 3Hints
- If capacity C works, any larger capacity works too, so feasibility is monotonic.
- The answer lies between max(weights) and sum(weights).
- Checking a capacity is a greedy O(n) simulation.
Approach
Binary search C in [max(w), sum(w)]. feasible(C): greedily fill each day until the next package would exceed C, counting the days needed; feasible if ≤ days. Find the smallest feasible C. O(n log(sum)).
Complexity
Time: O(n · log(sum − max)). Space: O(1).
Python solution
def shipWithinDays(weights, days):
def need(cap):
d, load = 1, 0
for w in weights:
if load + w > cap:
d += 1; load = 0
load += w
return d
lo, hi = max(weights), sum(weights)
while lo < hi:
mid = (lo + hi) // 2
if need(mid) <= days:
hi = mid
else:
lo = mid + 1
return loJavaScript solution
function shipWithinDays(weights, days) {
const need = (cap) => { let d = 1, load = 0; for (const w of weights) { if (load + w > cap) { d++; load = 0; } load += w; } return d; };
let lo = Math.max(...weights), hi = weights.reduce((a, b) => a + b, 0);
while (lo < hi) { const mid = Math.floor((lo + hi) / 2); if (need(mid) <= days) hi = mid; else lo = mid + 1; }
return lo;
}