~/problems / Binary search / Binary search on the answer

Capacity to Ship Packages Within D Days

medium ~25 min

Write ship_within_days(weights: list[int], days: int) -> int.

Packages must be shipped in the given order. Each day the ship is loaded with the next packages in line, as many as fit without the total weight going over the ship's capacity, and then it sails. Return the smallest capacity that ships every package within days days.

Example: weights = [3, 2, 2, 4, 1, 4], days = 3 gives 6 ([3, 2] | [2, 4] | [1, 4]). With days = 1 the answer is 16 (the total).

Constraints: 1 <= days <= len(weights) <= 5 * 10^4, 1 <= weights[i] <= 500.

Stepping the capacity up one at a time is too slow for the large test; aim for O(n log(sum(weights))).

Show hint

the capacity is at least max(weights) and at most sum(weights), and a bigger ship never needs more days. For a fixed capacity, the loading rule tells you the number of days in one pass.

Topic: Binary search on the answer. Monotonic feasibility check + search the smallest value that works.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc