Capacity To Ship Packages Within D Days

medium array binary search answer search

Problem

Given weights[i] for packages to be shipped in order, find the minimum ship capacity that lets all of them be delivered within D days. Packages must keep their original order and a single ship runs once per day.

Inputweights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], days = 5
Output15
Split as [1,2,3,4,5] [6,7] [8] [9] [10] — five days, max load 15.

def shipWithinDays(weights, days):
    def needed(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 needed(mid) <= days:
            hi = mid
        else:
            lo = mid + 1
    return lo
function shipWithinDays(weights, days) {
  const needed = (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 = (lo + hi) >> 1;
    if (needed(mid) <= days) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}
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) >>> 1;
            if (needed(weights, mid) <= days) hi = mid;
            else lo = mid + 1;
        }
        return lo;
    }
    private int needed(int[] w, int cap) {
        int d = 1, load = 0;
        for (int x : w) {
            if (load + x > cap) { d++; load = 0; }
            load += x;
        }
        return d;
    }
}
class Solution {
public:
    int shipWithinDays(vector<int>& w, int days) {
        int lo = 0, hi = 0;
        for (int x : w) { lo = max(lo, x); hi += x; }
        auto needed = [&](int cap) {
            int d = 1, load = 0;
            for (int x : w) {
                if (load + x > cap) { d++; load = 0; }
                load += x;
            }
            return d;
        };
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (needed(mid) <= days) hi = mid;
            else lo = mid + 1;
        }
        return lo;
    }
};
Time: O(n log S) where S = sum of weights Space: O(1)