Capacity to Ship Packages Within D Days — BS on Answer
Advertisement
Problem 317 · Capacity to Ship Packages Within D Days
Difficulty: Medium · Pattern: BS on Answer
Minimum capacity to ship all weights in days days, one continuous segment per day.
Solutions
# Python
def shipWithinDays(weights, days):
lo, hi = max(weights), sum(weights)
while lo < hi:
mid = (lo+hi)//2
day_count = 1; cur = 0
for w in weights:
if cur + w > mid: day_count += 1; cur = 0
cur += w
if day_count <= days: hi = mid
else: lo = mid+1
return lo
// Java
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, d=1, cur=0;
for (int w:weights) { if(cur+w>mid){d++;cur=0;} cur+=w; }
if (d<=days) hi=mid; else lo=mid+1;
}
return lo;
}
Complexity
- Time: O(n log(sum-max))
- Space: O(1)
Advertisement