Capacity To Ship Packages Within D Days (LeetCode 1011): Solution and Explanation
Packages with given weights sit on a conveyor belt and must be shipped in their original order. Each day the ship loads packages until the next one would exceed its capacity. Find the smallest capacity that ships everything within the given number of days.
Watch it run step by step
Try your own input and write the code →Intuition
First, notice that for a fixed capacity, the best way to load is greedy: put packages on today's ship until the next one does not fit, then start a new day. Filling each day as much as possible never hurts, because leaving room unused only pushes more weight onto later days. So checking whether a capacity works is a single linear pass that counts the days needed.
Now you need the smallest capacity that works. The brute force tries every capacity upward from the heaviest package, checking each one. The range can be huge, up to the total weight of all packages, so that is far too slow.
The useful fact is monotonicity. If a capacity ships everything within the allowed days, any bigger capacity does too, because every day can hold at least as much. So the capacities divide into a too small region followed by a big enough region, and you want the boundary, which is a job for binary search.
The bounds come straight from the problem. The capacity can never be less than the heaviest package, since that package must fit on some day. It never needs to be more than the total weight, which ships everything in one day. Binary search over that range, run the greedy check at each midpoint, and narrow toward the smallest capacity that passes.
Approach: Binary search on capacity with greedy check
- Set
l = max(weights)andr = sum(weights), and initializeres = r. - Define
canShip(cap): start with one ship andcurrCap = cap, and for each weight start a new ship whencurrCap - w < 0, then subtractw. canShipreturns whether the number of ships used is at mostdays.- While
l <= r, test the middle capacitycap = (l + r) // 2. - If it works, record
res = min(res, cap)and search smaller capacities withr = cap - 1; otherwise search larger ones withl = cap + 1. - Return
res.
Step-by-step example
weights = [1,2,3,4,5,6,7,8,9,10], days = 5
- The range is 10 to 55. Capacity 32 ships [1..7] (28) and [8,9,10] (27), so 2 days. It works,
res= 32, andr= 31. - Capacity 20 ships [1..5], [6,7], [8,9] and [10], so 4 days. It works,
res= 20, andr= 19. - Capacity 14 ships [1..4], [5,6], [7], [8], [9] and [10], so 6 days, too many. Set
l= 15. - Capacity 17 ships [1..5], [6,7], [8,9] and [10], so 4 days. It works,
res= 17, andr= 16. - Capacity 15 ships [1..5], [6,7], [8], [9] and [10], exactly 5 days. It works,
res= 15, andr= 14. - Now
l= 15 is greater thanr= 14, so the answer is 15.
Code: Python, Java, C++
1class Solution:
2 def shipWithinDays(self, weights: List[int], days: int) -> int:
3 l, r = max(weights), sum(weights)
4 res = r
5
6 def canShip(cap):
7 ships, currCap = 1, cap
8 for w in weights:
9 if currCap - w < 0:
10 ships += 1
11 currCap = cap
12 currCap -= w
13 return ships <= days
14
15 while l <= r:
16 cap = (l + r) // 2
17 if canShip(cap):
18 res = min(res, cap)
19 r = cap - 1
20 else:
21 l = cap + 1
22 return res1class Solution {
2 public int shipWithinDays(int[] weights, int days) {
3 int l = 0, r = 0;
4 for (int w : weights) {
5 l = Math.max(l, w);
6 r += w;
7 }
8 int res = r;
9
10 while (l <= r) {
11 int cap = l + (r - l) / 2;
12 if (canShip(cap, weights, days)) {
13 res = Math.min(res, cap);
14 r = cap - 1;
15 } else {
16 l = cap + 1;
17 }
18 }
19 return res;
20 }
21
22 private boolean canShip(int cap, int[] weights, int days) {
23 int ships = 1, currCap = cap;
24 for (int w : weights) {
25 if (currCap - w < 0) {
26 ships++;
27 currCap = cap;
28 }
29 currCap -= w;
30 }
31 return ships <= days;
32 }
33}1class Solution {
2public:
3 int shipWithinDays(vector<int>& weights, int days) {
4 int l = 0, r = 0;
5 for (int w : weights) {
6 l = max(l, w);
7 r += w;
8 }
9 int res = r;
10
11 while (l <= r) {
12 int cap = l + (r - l) / 2;
13 if (canShip(cap, weights, days)) {
14 res = min(res, cap);
15 r = cap - 1;
16 } else {
17 l = cap + 1;
18 }
19 }
20 return res;
21 }
22
23 bool canShip(int cap, vector<int>& weights, int days) {
24 int ships = 1, currCap = cap;
25 for (int w : weights) {
26 if (currCap - w < 0) {
27 ships++;
28 currCap = cap;
29 }
30 currCap -= w;
31 }
32 return ships <= days;
33 }
34};Time and space complexity
O(n log S)
Here S is the total weight. Binary search over the range from the heaviest package to S takes O(log S) iterations, and each greedy check is a pass over all n packages.
O(1)
Only counters and bounds are stored, apart from the input.
Other approaches
Linear search over capacities (time O(n × S), space O(1))
Try capacities from max(weights) upward and return the first that ships within the limit. It is correct but can take S iterations, each O(n), which is too slow for large weights.
Dynamic programming over splits (time O(days × n²), space O(days × n))
Let dp[d][i] be the minimum largest day load for shipping the first i packages in d days, using prefix sums to compute each day's load. It is the general partitioning DP and is much slower than the binary search here.
Common mistakes
- Starting the lower bound at 1 instead of the heaviest package. A capacity below the heaviest weight can never ship that package, and the greedy check would let that package overflow a ship and miscount the days.
- Starting the day count at 0 instead of 1 in the greedy check, which undercounts days by one.
- Reordering or sorting the weights. Packages must ship in the given order, so sorting changes the problem.
- Using
<=instead of<when deciding to start a new ship, which opens a new day even when the package fits exactly.
Frequently asked questions
Why does binary search work for Capacity To Ship Packages?
If a capacity can ship everything within the day limit, every larger capacity can too. That monotonic yes or no property means binary search can find the smallest capacity that works.
Why is the greedy loading optimal for a fixed capacity?
Loading as much as fits each day never makes later days heavier than any other valid plan would. So the greedy count is the minimum number of days needed for that capacity.
What are the search bounds?
The lower bound is the heaviest single package and the upper bound is the sum of all weights. The answer always lies in that range.
How is this related to Split Array Largest Sum?
They are the same problem in different words. Days are the number of subarrays and capacity is the largest subarray sum, so the same binary search applies.