SDE & MLE Prep

1011. Capacity To Ship Packages Within D Days

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