Capacity to Ship Packages in D Days
MediumBigger capacity → fewer days
Guess a ship size; if everything fits in the days allowed try smaller, otherwise bigger.
The idea
A larger ship finishes in fewer days, so days-needed is monotone in capacity. Search the least capacity that ships within D days.
5
6
7
8
9
10
11
12
13
14
15
0
1
2
3
4
5
6
7
8
9
10
candidates11
Step 1 of 4. Brute force: try every ship capacity until the load fits in 3 days. Values: 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15. candidates 11.
1/4
Brute force
timeO(sum·n)spaceO(1)
Try every capacity.
1let best = -1;2for (let cap = maxW; cap <= sum && best < 0; cap++)3 if (daysNeeded(cap) <= days) best = cap;4return best;Input
- array
- [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Memory
- try
- —
- candidates
- 11
- capacity
- —
Output
- capacity
- —
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], days = 5
- Output:
- 15
- Explanation:
- A ship of size 15 finishes in 5 days.
Example 2
- Input:
- weights = [3, 2, 2, 4, 1, 4], days = 3
- Output:
- 6
- Explanation:
- Capacity 6 splits the load into 3 days.
Example 3
- Input:
- weights = [1, 2, 3, 1, 1], days = 4
- Output:
- 3
- Explanation:
- Capacity 3 fits in 4 days.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.