Capacity To Ship Packages Within D Days Solution
Find the minimum ship capacity that lets us deliver all packages in order within a fixed number of days.
Problem Statement
Packages must stay in their original order. If the ship capacity is C, we greedily load as many consecutive packages as fit each day. We want the smallest capacity whose simulation finishes within days.
Test Every Capacity β O(n Β· sum(weights))
We could try capacities starting from max(weights) upward, simulate shipping for each, and return the first one that works.
C works, every larger capacity also works. That monotonic boundary is exactly what binary search needs.Binary Search on Capacity β O(n log(sum-max))
The minimum possible capacity is max(weights) because the heaviest package must fit. The maximum possible capacity is sum(weights) because one day could carry everything. Binary search that interval and use a greedy simulation as the feasibility function.
- Search space:
[max(weights), sum(weights)] - Feasibility check: greedily pack consecutive weights until the next one would overflow capacity, then start a new day
- If the days used are
<= days, the capacity is feasible - Feasible β search left for a smaller capacity
- Infeasible β search right for a larger capacity
- βMinimum capacity / speed / rate / threshold such that a greedy simulation worksβ is the classic binary-search-on-answer pattern.
- Write the monotonic check first, then search the answer space.
Visual Walkthrough
Trace the sample input.
Code β Java & Python
Complexity Analysis
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| Test every capacity | O(n Β· sum(weights)) | O(1) | Too slow when the answer range is large. |
| Binary search on answer β optimal | O(n log(sum(weights) - max(weights))) | O(1) | Each candidate capacity is checked with one greedy scan. |
Edge Cases & Pitfalls
| Case | Expected behavior | Why it matters |
|---|---|---|
| One package heavier than capacity | Impossible for that capacity | This is why the lower bound is max(weights). |
days == 1 | Answer is sum(weights) | Everything must ship together. |
days == weights.length | Answer is max(weights) | You can ship at most one package per day. |
| Reordering packages | Not allowed | The greedy simulation must preserve the original order. |
| Feasible mid | Search left | We need the minimum feasible capacity, not any feasible capacity. |