1011. Capacity To Ship Packages Within D Days
Asked at 20Amazon61Bloomberg46Microsoft46Meta45Google44Apple30Agoda89Snap45Apollo.io100DP world100Zeta74Myntra64InMobi62Expedia54Flipkart43Walmart Labs43Oracle41Visa39Goldman Sachs36Uber22
Problem
Packages with weights must ship in the given order. Each day the ship is loaded with consecutive packages up to its capacity. Return the smallest capacity that ships everything within days days.
Example: weights = [1,2,3,4,5,6,7,8,9,10], days = 5 → 15
Constraints: n ≤ 5·10⁴.
Capacity in [max(w), sum(w)]. days(cap) (greedy fill) decreases with cap → smallest cap with days ≤ D.
Complexity: O(n log sum).
class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def need(cap):
d, load = 1, 0
for w in weights:
if load + w > cap:
d, load = d + 1, 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 lo
assert Solution().shipWithinDays([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5) == 15
assert Solution().shipWithinDays([3, 2, 2, 4, 1, 4], 3) == 6
class Solution {
public int shipWithinDays(int[] weights, int days) {
int lo = 0, hi = 0;
for (int w : weights) { lo = Math.max(lo, w); hi += w; }
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (need(weights, mid) <= days) hi = mid; else lo = mid + 1;
}
return lo;
}
private int need(int[] weights, int cap) {
int d = 1, load = 0;
for (int w : weights) {
if (load + w > cap) { d++; load = 0; }
load += w;
}
return d;
}
}
func shipWithinDays(weights []int, days int) int {
need := func(capacity int) int {
d, load := 1, 0
for _, w := range weights {
if load+w > capacity {
d, load = d+1, 0
}
load += w
}
return d
}
lo, hi := 0, 0
for _, w := range weights {
lo = max(lo, w)
hi += w
}
for lo < hi { // smallest capacity that needs <= days
mid := lo + (hi-lo)/2
if need(mid) <= days {
hi = mid
} else {
lo = mid + 1
}
}
return lo
}