Packages wait in a line, and weights[i] is the weight of package i. A ship carries them over several days. Each day it takes the next packages from the front of the line, in order, as long as their total weight stays within the ship's capacity.
Find the smallest capacity that gets every package shipped in at most days days.
Example 1
Input: weights = [4, 2, 5, 1, 3, 6], days = 3 Output: 9 Why: [4, 2], [5, 1, 3], [6]; capacity 8 needs 4 days
2 more examples and the constraints
Example 2
Input: weights = [7, 1, 1, 1], days = 2 Output: 7 Why: the 7 must fit on its own; then [1, 1, 1] is one day
Example 3
Input: weights = [2, 5, 3], days = 1 Output: 10 Why: one day means everything at once
Constraints
- 1 ≤ days ≤ length of weights ≤ 50,000
- 1 ≤ weights[i] ≤ 500
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every capacityO(n · S)
- Binary search the capacityO(n log S)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 50,000 packages and 1 day | Verdict |
|---|---|---|---|
| Try every capacity | O(n · S) | Mention it, then move on | |
| Binary search the capacity | O(n log S) | Best; about 25 passes |
n = number of packages, S = total weight.
Edge cases to test
- One day. The answer is the total weight: everything ships together.
- As many days as packages. The answer is the heaviest package: one per day is enough.
- One very heavy package. It sets the lower bound, as in [7, 1, 1, 1] with 2 days.
- Single package. [5] with 1 day needs capacity 5.
Common mistakes
- Starting the search at 1 instead of the heaviest package, so the day count breaks on a package that never fits.
- Setting hi = mid - 1 when mid works, which can skip the answer.
- Counting days by starting a new day after a full load instead of before the package that overflows.
How to talk through it
- 1Clarify. Must the order be kept? Can a package be split? (Yes; no.)
- 2Check one capacity. Greedy loading counts the days a given capacity needs, in O(n).
- 3Notice it is monotone. A bigger ship never needs more days, so the yes answers form a suffix.
- 4Binary search it. Between the heaviest package and the total. O(n log S) time, O(1) space.
- 5Test out loud. Run days = 1, days = n and one heavy package before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?