Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Binary search

Smallest ship that clears the backlog in D days

Medium · Target 20 minutes · Binary search · Type asked atGoldman SachsGoogle

Packages must be shipped in the order given. weights[i] is the weight of the i-th package. Each day the ship is loaded with a run of packages from the front, without exceeding its capacity. Return the smallest capacity that clears every package within days days.

Examples

InputOutputWhy
weights = [1,2,3,4,5,6,7,8,9,10], days = 515Days of 1–5, 6–7, 8, 9, 10.
weights = [3,2,2,4,1,4], days = 363+2, 2+4, 1+4.
weights = [1,2,3,1,1], days = 43A capacity of 2 needs five days.

Constraints

  • 1 ≤ days ≤ n ≤ 5 × 10⁴
  • 1 ≤ weights[i] ≤ 500
  • Packages keep their order

Hints

Hint 1

Ask the easier question first: given a capacity C, can you finish in the allowed number of days? That is one greedy pass.

Hint 2

If capacity C works, does C + 1 also work? That monotonicity is what makes binary search legal.

Hint 3

The answer is between max(weights) — a single package must fit — and sum(weights), which is one day.

Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.