15% off all plans & roadmaps Use code
See plansCapacity To Ship Packages Within D Days
- LeetCode 1011
- Medium
- Binary Search Patterns
- On Answer / Condition Function
Updated
TL;DR: You need the smallest ship capacity that moves every package, in order, within the day limit. Binary search the capacity, and check each candidate with a greedy scan that fills each day as far as it can.
Problem
A conveyor belt carries packages from one port to another. The ith package on the belt weighs weights[i], and all the packages must ship within days days.
Each day, we load the ship with packages from the belt, in the order given by weights. We may not load more weight than the ship's maximum capacity. Return the least capacity that ships all the packages within days days.
Example 1
Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5 Output: 15 Explanation: A capacity of 15 is the minimum to ship all the packages in 5 days, like this: 1st day: 1, 2, 3, 4, 5. 2nd day: 6, 7. 3rd day: 8. 4th day: 9. 5th day: 10. The cargo must ship in the order given. A capacity of 14 is not allowed with a split such as (2, 3, 4, 5), (1, 6, 7), (8), (9), (10).
Example 2
Input: weights = [3,2,2,4,1,4], days = 3 Output: 6 Explanation: A capacity of 6 is the minimum to ship all the packages in 3 days, like this: 1st day: 3, 2. 2nd day: 2, 4. 3rd day: 1, 4.
Example 3
Input: weights = [1,2,3,1,1], days = 4 Output: 3 Explanation: 1st day: 1. 2nd day: 2. 3rd day: 3. 4th day: 1, 1.
Constraints
1 <= days <= weights.length <= 5 * 10^41 <= weights[i] <= 500
Constraints that matter
- The weights are at most 500 and the array holds up to 5 * 10^4 packages, so the sum can reach 2.5 * 10^7. Trying every capacity in that range with a full scan each time is too slow.
- The capacity can never be below the heaviest package. That gives a natural lower bound of max(weights).
- days can be as small as 1, so the answer can be as large as the total weight. That gives the upper bound sum(weights).
- The order is fixed. You cannot sort or regroup the packages, so the check has to scan them in sequence.
Hints
Hint 1
The question asks for a capacity, which is a number inside a known range.
Hint 2
Try every capacity from the heaviest package up to the total weight, in increasing order.
Solution
Intuition
The question asks for a capacity, which is a number inside a known range. The smallest possible capacity is max(weights), and the largest useful one is sum(weights). When you search for a value across a known range, the pattern is binary search on the answer.
Picture a row of numbered gates, where every gate from some point onward opens and every gate before it stays shut. The gate numbers are the candidate capacities, and the inspector who tests one gate is the greedy day count.
The second part is a yes or no question: can this capacity ship everything within days days? A larger capacity never needs more days than a smaller one. So the answers across the range look like no, no, no, yes, yes, yes. You only need to find the first yes.
The yes or no check must be fast. For a fixed capacity, a greedy scan works. Load each day with packages in order until the next one would overflow, then start a new day. Each day takes the longest prefix that fits, so no other split uses fewer days for that capacity.
Worked example
Input: weights = [3, 2, 2, 4, 1, 4], days = 3 Output: 6 Explanation: The heaviest package weighs 4, so the capacity must be at least 4. A capacity of 6 packs the packages into three days: [3, 2], [2, 4], [1, 4]. A capacity of 5 needs four days, so 6 is the smallest value that works.
Approach 1: Brute force
Try every capacity from the heaviest package up to the total weight, in increasing order. For each capacity, run the greedy day count. Return the first capacity that finishes within days days.
This is correct. The first feasible capacity is the smallest one, so returning it gives the minimum. The cost comes from how many capacities you try, and each try rescans the whole array.
Steps
- Compute
maxWas the largest weight andtotalas the sum of all weights. - For each capacity from
maxWtototal, in increasing order, run the day count. - Start
daysNeededat 1 andloadat 0. - For each weight, if
load + wis more than the capacity, add a day and setloadto 0. Then addwtoload. - If
daysNeededis at mostdays, return the capacity. - If no capacity works, return
total. Valid input never reaches this line.
Dry run
Start at capacity 4, the heaviest package. Day 1 takes 3, because 3 + 2 = 5 is more than 4. Day 2 takes 2, 2, because 2 + 2 = 4 fits. Day 3 takes 4, day 4 takes 1 and day 5 takes 4.
That is five days, which is more than 3, so 4 fails.
Try capacity 5. Day 1 takes 3, 2. Day 2 takes 2 alone, since 2 + 4 is more than 5. Day 3 takes 4, 1, and day 4 takes 4 alone. That is four days, so 5 fails.
Try capacity 6. Day 1 takes 3, 2. Day 2 takes 2, 4. Day 3 takes 1, 4. That is three days, which is at most 3, so the function returns 6.
Complexity
| Time | O(N * S) |
|---|---|
| Space | O(1) |
Let N be the number of packages and S the sum of the weights. The outer loop tries at most S capacities, since the range runs from max(weights) to S. Each check reads the array once with constant work per package, so one check costs O(N).
Multiplying the two counts gives O(N * S) time. The worst case is days = 1, where the loop runs all the way to S. The extra space is O(1).
PythonTested in our runner
class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
# Try each capacity in increasing order and return the first that works
max_w = max(weights)
total = sum(weights)
for capacity in range(max_w, total + 1):
days_needed = 1
load = 0
for w in weights:
if load + w > capacity:
days_needed += 1
load = 0
load += w
if days_needed <= days:
return capacity
return totalJavaTested in our runner
class Solution {
public int shipWithinDays(int[] weights, int days) {
int maxW = 0;
int total = 0;
for (int w : weights) {
maxW = Math.max(maxW, w);
total += w;
}
// Try each capacity in increasing order
for (int capacity = maxW; capacity <= total; capacity++) {
if (daysFor(weights, capacity) <= days) {
return capacity;
}
}
return total;
}
private int daysFor(int[] weights, int capacity) {
int daysNeeded = 1;
int load = 0;
for (int w : weights) {
if (load + w > capacity) {
daysNeeded++;
load = 0;
}
load += w;
}
return daysNeeded;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int shipWithinDays(vector<int>& weights, int days) {
int maxW = 0;
int total = 0;
for (int w : weights) {
maxW = w > maxW ? w : maxW;
total += w;
}
// Try each capacity in increasing order
for (int capacity = maxW; capacity <= total; capacity++) {
if (daysFor(weights, capacity) <= days) {
return capacity;
}
}
return total;
}
private:
int daysFor(const vector<int>& weights, int capacity) {
int daysNeeded = 1;
int load = 0;
for (int w : weights) {
if (load + w > capacity) {
daysNeeded++;
load = 0;
}
load += w;
}
return daysNeeded;
}
};JavaScriptTested in our runner
var shipWithinDays = function(weights, days) {
let maxW = 0;
let total = 0;
for (const w of weights) {
maxW = Math.max(maxW, w);
total += w;
}
const daysFor = (capacity) => {
let daysNeeded = 1;
let load = 0;
for (const w of weights) {
if (load + w > capacity) {
daysNeeded++;
load = 0;
}
load += w;
}
return daysNeeded;
};
// Try each capacity in increasing order
for (let capacity = maxW; capacity <= total; capacity++) {
if (daysFor(capacity) <= days) {
return capacity;
}
}
return total;
};GoTested in our runner
func shipWithinDays(weights []int, days int) int {
maxW, total := 0, 0
for _, w := range weights {
if w > maxW {
maxW = w
}
total += w
}
// Try each capacity in increasing order
for capacity := maxW; capacity <= total; capacity++ {
daysNeeded, load := 1, 0
for _, w := range weights {
if load+w > capacity {
daysNeeded++
load = 0
}
load += w
}
if daysNeeded <= days {
return capacity
}
}
return total
}C#Tested in our runner
public class Solution {
public int shipWithinDays(int[] weights, int days) {
int maxW = 0;
int total = 0;
foreach (int w in weights) {
maxW = Math.Max(maxW, w);
total += w;
}
// Try each capacity in increasing order
for (int capacity = maxW; capacity <= total; capacity++) {
if (DaysFor(weights, capacity) <= days) {
return capacity;
}
}
return total;
}
private int DaysFor(int[] weights, int capacity) {
int daysNeeded = 1;
int load = 0;
foreach (int w in weights) {
if (load + w > capacity) {
daysNeeded++;
load = 0;
}
load += w;
}
return daysNeeded;
}
}The On Answer / Condition Function infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
On Answer / Condition Function
Part of Binary Search Patterns
Approach 2: Binary search on the answerOptimalOn Answer / Condition Function
What's slow: brute force asks the yes or no question at every capacity from the heaviest package upward. Most of those checks repeat what a neighbouring check already showed.
The insight that fixes it: the answers switch from no to yes exactly once, and they never switch back. A binary search finds that switch. Each check cuts the candidate range in half, so you need about log S checks instead of up to S.
Keep right at a value known to work, and move left up past values known to fail. When the two meet, that value is the smallest capacity that works.
Steps
- Set
leftto max(weights) andrightto sum(weights). - While
leftis less thanright, computemid = left + (right - left) // 2. - Run the greedy day count for capacity
mid. Start at 1 day and a load of 0. - If the day count is at most
days, setright = mid. - Otherwise set
left = mid + 1. - When the loop ends, return
left.
Dry run
Start with left = 4 and right = 16, the sum of the weights. Each row shows one iteration of the loop.
| Step | left | right | mid | days needed at mid | feasible? | update |
|---|---|---|---|---|---|---|
| 1 | 4 | 16 | 10 | 2 | yes | right = 10 |
| 2 | 4 | 10 | 7 | 3 | yes | right = 7 |
| 3 | 4 | 7 | 5 | 4 | no | left = 6 |
| 4 | 6 | 7 | 6 | 3 | yes | right = 6 |
| 5 | 6 | 6 | stop | none | none | return 6 |
Row 1 groups [3, 2, 2] and [4, 1, 4]. Row 2 groups [3, 2, 2], [4, 1], [4].
Row 3 is the key case. Capacity 5 needs four days, so every capacity up to 5 fails, and the answer must be above 5. Row 4 confirms that 6 works. The loop ends with left = right = 6, which matches the expected output.
Complexity
| Time | O(N log S) |
|---|---|
| Space | O(1) |
Let N be the number of packages and S the sum of the weights. The range from left to right starts at most S wide and halves on each iteration, so there are about log2(S) + 1 iterations. For S = 2.5 * 10^7 that is about 25 checks.
Each check reads the array once with constant work per package, so it costs O(N). The total time is O(N log S). The loop stores only left, right, mid, the load and a day counter, so the extra space is O(1).
PythonTested in our runner
class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def can_ship(capacity: int) -> bool:
# Greedy: fill each day as far as possible in order
days_needed = 1
load = 0
for w in weights:
if load + w > capacity:
days_needed += 1
load = 0
load += w
return days_needed <= days
# The answer lies between the heaviest package and the total weight
left = max(weights)
right = sum(weights)
while left < right:
mid = left + (right - left) // 2
if can_ship(mid):
right = mid # mid works, so the answer is mid or smaller
else:
left = mid + 1 # mid fails, so the answer is larger
return leftJavaTested in our runner
class Solution {
public int shipWithinDays(int[] weights, int days) {
int left = 0;
int right = 0;
for (int w : weights) {
left = Math.max(left, w);
right += w;
}
while (left < right) {
int mid = left + (right - left) / 2;
if (canShip(weights, days, mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
private boolean canShip(int[] weights, int days, int capacity) {
int daysNeeded = 1;
int load = 0;
for (int w : weights) {
if (load + w > capacity) {
daysNeeded++;
load = 0;
}
load += w;
}
return daysNeeded <= days;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int shipWithinDays(vector<int>& weights, int days) {
int left = 0;
int right = 0;
for (int w : weights) {
left = w > left ? w : left;
right += w;
}
while (left < right) {
int mid = left + (right - left) / 2;
if (canShip(weights, days, mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
private:
bool canShip(const vector<int>& weights, int days, int capacity) {
int daysNeeded = 1;
int load = 0;
for (int w : weights) {
if (load + w > capacity) {
daysNeeded++;
load = 0;
}
load += w;
}
return daysNeeded <= days;
}
};JavaScriptTested in our runner
var shipWithinDays = function(weights, days) {
let left = 0;
let right = 0;
for (const w of weights) {
left = Math.max(left, w);
right += w;
}
const canShip = (capacity) => {
let daysNeeded = 1;
let load = 0;
for (const w of weights) {
if (load + w > capacity) {
daysNeeded++;
load = 0;
}
load += w;
}
return daysNeeded <= days;
};
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
if (canShip(mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
};GoTested in our runner
func shipWithinDays(weights []int, days int) int {
left, right := 0, 0
for _, w := range weights {
if w > left {
left = w
}
right += w
}
canShip := func(capacity int) bool {
daysNeeded, load := 1, 0
for _, w := range weights {
if load+w > capacity {
daysNeeded++
load = 0
}
load += w
}
return daysNeeded <= days
}
for left < right {
mid := left + (right-left)/2
if canShip(mid) {
right = mid
} else {
left = mid + 1
}
}
return left
}C#Tested in our runner
public class Solution {
public int shipWithinDays(int[] weights, int days) {
int left = 0;
int right = 0;
foreach (int w in weights) {
left = Math.Max(left, w);
right += w;
}
while (left < right) {
int mid = left + (right - left) / 2;
if (CanShip(weights, days, mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
private bool CanShip(int[] weights, int days, int capacity) {
int daysNeeded = 1;
int load = 0;
foreach (int w in weights) {
if (load + w > capacity) {
daysNeeded++;
load = 0;
}
load += w;
}
return daysNeeded <= days;
}
}Common mistakes
- Starting
leftat 0 or 1. A capacity below the heaviest package can never load that package, so the check sees values it should never test. Startleftat max(weights). - Writing
right = mid - 1after a feasible check. That dropsmid, which can be the smallest valid capacity. Keep it withright = mid. - Writing
left = midafter an infeasible check. Whenleftandrightare one apart,midequalsleftand the loop never ends. Useleft = mid + 1. - Resetting
load = 0for a new day and forgetting to add the package that did not fit. That package starts the new day, so add its weight to the new load. - Starting
daysNeededat 0. The first day is always used, so the count starts at 1. Starting at 0 undercounts the days and accepts capacities that are too small. - Testing
daysNeeded < days. The problem allows exactlydaysdays, so the check isdaysNeeded <= days.
Edge cases
daysequals the number of packages. Each package gets its own day, so the answer is max(weights).daysequals 1. Everything ships in one load, so the answer is sum(weights).- A single package,
weights = [7]withdays = 1. The answer is 7. - All weights equal,
weights = [5, 5, 5, 5]withdays = 2. Two packages fit per day, so the answer is 10. - Many packages at the maximum weight, 50000 copies of 500 with
days = 50000. Each package gets its own day, so the answer is 500. - The largest sum, 50000 packages of weight 500 with
days = 1. The answer is 2.5 * 10^7, which fits in a 32-bit int.
Follow-ups interviewers ask
- What if the packages could ship in any order?
- The problem becomes bin packing with a fixed number of bins, which is NP-hard. The greedy check depends on the fixed order, so it no longer gives the minimum. You would need a different method, and this binary search would not guarantee the answer.
- Can you solve it in O(1) extra space?
- The optimal approach already uses O(1) extra space. It keeps
left,right,mid, a running load and a day counter. The input array is read in place. - What if you must print the day-by-day split?
- Run the greedy check once more at the answer capacity. Start a new group every time the next package would overflow the load. Building the groups takes O(N) output space, and the working memory stays O(1).
Capacity To Ship Packages Within D Days FAQ
What is the time complexity of Capacity To Ship Packages Within D Days?
The binary search version runs in O(N log S) time, where N is the number of packages and S is the sum of the weights. The brute force version runs in O(N * S) time. The binary search version is the one to write in an interview.
Why use binary search for Capacity To Ship Packages Within D Days?
The answer is a capacity, and a check tells you whether a capacity works. If one capacity works, every larger one works too. So the answers switch from no to yes once, and binary search finds that switch in about log S checks.
Can Capacity To Ship Packages Within D Days be solved in O(1) extra space?
Yes. The binary search keeps a few integers, and the greedy check keeps a day counter and a running load. Nothing grows with the input size.
Why not sort the weights first?
Sorting breaks the required shipping order. The day split depends on the sequence, so a sorted array can need a different number of days. The problem does not allow reordering.
Why is a monotonic stack not the right tool here?
A monotonic stack answers next-greater or next-smaller questions for each element. This problem asks for one capacity that splits the whole sequence into groups. No stack tracks that threshold.
Does the greedy day split use the fewest days?
Yes, for any fixed capacity. Each day loads the longest prefix that fits, so no later cut can use fewer days. That is why the check can trust its day count.
Asked at
See which companies ask this — Pro
Related problems
- Koko Eating Bananas · same technique: On Answer / Condition Function
- Maximum Candies Allocated to K Children · same technique: On Answer / Condition Function
- Minimized Maximum of Products Distributed to Any Store · same technique: On Answer / Condition Function
- Minimum Limit of Balls in a Bag · same technique: On Answer / Condition Function
- Minimum Number of Days to Make m Bouquets · same technique: On Answer / Condition Function
- Median of Two Sorted Arrays · next harder, same pattern
- Search in Rotated Sorted Array · same pattern: Binary Search Patterns
- Find Minimum in Rotated Sorted Array · same pattern: Binary Search Patterns
- Search a 2D Matrix · same pattern: Binary Search Patterns
- Find K Closest Elements · same pattern: Binary Search Patterns