Full answer
Problem
Packages with weights must be shipped in the given order. Each day the ship carries a contiguous run of packages whose total does not exceed its capacity. Return the least capacity that ships everything within days days.
Example: weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], days = 5 gives 15: [1..5] [6, 7] [8] [9] [10].
Constraints: 1 <= days <= len(weights) <= 5 x 10^4 (more days than packages also works: the answer is then the largest weight), 1 <= weights[i] <= 500.
Brute force
Try every way to cut the list into at most days contiguous parts and take the smallest maximum part: exponential, about C(n - 1, d - 1) partitions. The test uses it as a reference for tiny inputs.
A DP over (prefix, parts) is O(n^2 x d), still too slow for n = 5 x 10^4.
Optimal approach
- Bounds:
lo = max(weights)(the heaviest package must fit),hi = sum(weights)(one day). days_needed(c): greedy pass; add packages to today's load until the next one would exceedc, then start a new day.- Binary search for the smallest
cwithdays_needed(c) <= days.
Why it works
Greedy is optimal for a fixed capacity: filling each day as much as possible can only push later cuts further right, so it never uses more days than any other valid schedule (an exchange argument). The predicate "capacity c is enough" is monotonic, since a larger ship can follow the same schedule. Binary search finds the first capacity where the predicate becomes true.
Complexity
O(n log S) time, where S = sum(weights): at most about 25 iterations for S = 2.5 x 10^7, each O(n). O(1) space.
Code
def ship_within_days(weights, days):
"""Least ship capacity to send packages in order within `days` days."""
def days_needed(capacity):
used, load = 1, 0
for w in weights:
if load + w > capacity: # start a new day
used += 1
load = 0
load += w
return used
lo, hi = max(weights), sum(weights) # must carry the heaviest; never need more than all
while lo < hi:
mid = (lo + hi) // 2
if days_needed(mid) <= days:
hi = mid
else:
lo = mid + 1
return lo
def brute(weights, days):
from itertools import combinations
n = len(weights)
best = sum(weights)
for cuts in range(min(days, n)):
for pos in combinations(range(1, n), cuts):
bounds = (0,) + pos + (n,)
best = min(best, max(sum(weights[a:b]) for a, b in zip(bounds, bounds[1:])))
return best
if __name__ == "__main__":
for f in (ship_within_days, brute):
assert f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5) == 15
assert f([3, 2, 2, 4, 1, 4], 3) == 6
assert f([1, 2, 3, 1, 1], 4) == 3
assert f([7], 1) == 7
assert f([7, 2, 5, 10, 8], 2) == 18
assert f([1, 1, 1], 10) == 1
print("all tests passed")Save as a31_ship_packages.py and run python3 a31_ship_packages.py. It prints all tests passed (Python 3.13.5).
Edge cases
One package. days >= len(weights) (answer is the largest weight). days == 1 (answer is the total). Equal weights. Starting lo at 0 or 1 instead of max(weights) still terminates, but the greedy check must then handle a package larger than capacity; starting at the maximum avoids that case.
Pattern
Binary search on the answer with a greedy feasibility check. The same pattern solves split array largest sum, allocating books to students, painters' partition and minimising the maximum distance between gas stations.
def ship_within_days(weights, days):
"""Least ship capacity to send packages in order within `days` days."""
def days_needed(capacity):
used, load = 1, 0
for w in weights:
if load + w > capacity: # start a new day
used += 1
load = 0
load += w
return used
lo, hi = max(weights), sum(weights) # must carry the heaviest; never need more than all
while lo < hi:
mid = (lo + hi) // 2
if days_needed(mid) <= days:
hi = mid
else:
lo = mid + 1
return lo
def brute(weights, days):
from itertools import combinations
n = len(weights)
best = sum(weights)
for cuts in range(min(days, n)):
for pos in combinations(range(1, n), cuts):
bounds = (0,) + pos + (n,)
best = min(best, max(sum(weights[a:b]) for a, b in zip(bounds, bounds[1:])))
return best
if __name__ == "__main__":
for f in (ship_within_days, brute):
assert f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5) == 15
assert f([3, 2, 2, 4, 1, 4], 3) == 6
assert f([1, 2, 3, 1, 1], 4) == 3
assert f([7], 1) == 7
assert f([7, 2, 5, 10, 8], 2) == 18
assert f([1, 1, 1], 10) == 1
print("all tests passed")Greedy day counter plus binary search; an exhaustive partition search checks the same tests.
Complexity
Time: O(n log S), S = sum(weights). Space: O(1). The exhaustive brute force is exponential and is used only as a test reference.
By level
Fresher: Writes the greedy day counter and searches capacities with binary search, testing the example. Should explain why the lower bound is the heaviest package.
Mid: Justifies the greedy with an exchange argument, chooses tight bounds and connects to split array largest sum. Explains why the greedy count is optimal for a fixed capacity.
Senior: Compares with DP formulations, discusses reordering (which becomes bin packing and NP-hard) and real-valued variants. Explains why the reordered version becomes a much harder problem.
Key points
- Feasibility for a fixed capacity is a greedy pass
- Larger capacity never needs more days: monotonic
- Bounds are max(weights) and sum(weights)
- Binary search the first feasible capacity
- Same problem as split array largest sum
Common mistakes
- Lower bound below the heaviest package
- Reordering packages
- Off-by-one in counting days (start with 1 day)
- Using hi = mid - 1 when mid is feasible
Follow-ups
- How would you return the actual split?
- What if packages could be reordered?
- How does this relate to the painters' partition problem?
Tips
- State the bounds and justify each
- Explain why greedy is optimal for a fixed capacity
- Mention the split array equivalence
Evaluation rubric
- Correct bounds and greedy check
- Correct binary search
- Justifies monotonicity and greedy
- Correct complexity