Python coding

Smallest truck that meets the deadline

Packages leave a warehouse in a fixed order; weights[i] is the weight of package i. Each day one truck loads packages in order until the next one would exceed its capacity, then departs. Return the smallest integer capacity that ships every package within days days.

Constraints: at least one package, every weight ≥ 1, days ≥ 1. Aim for O(n log(sum(weights))) time.

Besides the tests, one large input (750 packages) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • min_capacity([1,2,3,4,5,6,7,8,9,10], 5) → 15
  • min_capacity([3,2,2,4,1,4], 3) → 6
  • min_capacity([1,2,3,1,1], 4) → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

If capacity c ships everything in time, so does c + 1. A monotonic yes/no question means you can binary search the answer itself.

Hint 2

Search between max(weights) and sum(weights). Check a guess greedily: fill each day until the next package does not fit, and count the days.

Solution and why it works
pythonO(n log(sum(weights))) · O(1)
def min_capacity(weights: list[int], days: int) -> int:
    def fits(cap: int) -> bool:
        used, load = 1, 0
        for w in weights:
            if load + w > cap:
                used, load = used + 1, 0
            load += w
        return used <= days

    lo, hi = max(weights), sum(weights)
    while lo < hi:
        mid = (lo + hi) // 2
        if fits(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo

Feasibility is monotonic: a capacity that works keeps working as it grows, so binary search finds the first one that works between max(weights) and sum(weights), checking each guess with an O(n) greedy count: O(n log(sum)). The lower bound is the trap: below max(weights) the greedy check "fits" a package that cannot fit, and the search returns a capacity that is too small.

Related lab: Loops in motion