Problem Statement

Capacity To Ship Packages Within D Days

A conveyor belt has a line of packages. You must ship all of them within a set number of days. The package at position i weighs weights[i]. Each day you load packages onto the ship in order, left to right, without skipping any. The ship can only carry so much weight in one day, and that limit is called its capacity. The question is: what is the smallest capacity that still lets you ship everything within the allowed number of days? A bigger ship finishes faster but costs more, so we want the smallest ship that still gets the job done on time.

mediumBinary SearchBinary SearchTime: O(n log(sum)) · Space: O(1)

Signals to notice

minimize the maximum capacitymust ship within D daysbinary search on answer

Brute force first

Try every capacity from max(weights) to sum(weights). Linear search through all feasible capacities. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Binary search on the capacity. For each candidate, greedily simulate shipping: pack packages until the day's capacity is full, then start a new day. If you need ≤ D days, the capacity works. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Trace it on weights=[3,2,2,4,1,4], days=3

init: left=max=4, right=sum=16 (search space for capacity)
mid=10: greedy needs 2 days (2<=3) -> feasible, shrink right=10
mid=7: greedy needs 3 days (3<=3) -> feasible, shrink right=7
mid=5: greedy needs 4 days (4>3) -> infeasible, raise left=6
mid=6: pack [3,2],[2,4]? -> 3 days (3<=3) -> feasible, right=6
left==right==6: loop ends
return left = 6

What must stay true

If capacity c works (ships in ≤ D days), any capacity > c also works. This monotonicity validates binary search. The minimum valid capacity is the answer. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Shape of the loop

left = max(weights); right = sum(weights)
while left < right:
    mid = (left + right) // 2
    days_needed = greedily pack weights, new day when cur+w > mid
    if days_needed <= days: right = mid   # capacity works, try smaller
    else: left = mid + 1                   # too tight, need more
return left

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Setting the lower bound to 1 instead of max(weights) — you can't split a package, so the minimum capacity must be at least the heaviest package. The fix is usually to return to the meaning of each move, not just the steps themselves.

Binary Search Pattern