Editorial
Core insight
Capacity To Ship Packages Within D Days · Binary Search Patterns
Core Insight for Capacity To Ship Packages Within D Days
The key intuition is recognizing that the property "can ship within D days" is monotonic with respect to capacity.
- Monotonicity: If a ship capacity of
Cis sufficient to ship all packages withinDdays, then any capacityC + 1is also sufficient (it will takeDdays or fewer). Conversely, if capacityCis insufficient, then any capacityC - 1is also insufficient. - Search Space Definition:
- Lower Bound (
left): The capacity cannot be smaller than the heaviest single package,max(weights). If it were, that package could never be loaded. - Upper Bound (
right): The capacity never needs to exceed the total weight of all packages,sum(weights). This capacity guarantees shipping in exactly 1 day.
- Lower Bound (
- Condition Function: We can define a function
feasible(capacity)that returnstrueif the packages can be shipped withindaysusing that capacity, andfalseotherwise. This function runs in linear time .
Visual Description:
Imagine the search space as a sorted array of candidate capacities ranging from max(weights) to sum(weights). If we apply the feasible function to each value, the results would look like a sequence of False values followed by a sequence of True values (e.g., [F, F, F, T, T, T]). Our goal is to find the index of the first True in this virtual array.

Deep dive
Full breakdown
Full reasoning, pitfalls, and implementation flow
LeetCode 1011: Capacity To Ship Packages Within D Days Solution & Explanation
Problem Overview
TL;DR: Perform a binary search on the range of possible ship capacities, using a greedy simulation to verify if a specific capacity allows shipping all packages within the deadline.
The problem asks us to determine the minimum ship capacity required to transport a sequence of packages within a specified number of days, days. The packages must be shipped in the order they appear on the conveyor belt. We are given an array weights representing the packages and an integer days. We must return the lowest integer capacity such that the shipping process takes no more than days.
This is a classic optimization problem found in the LeetCode 1011: Capacity To Ship Packages Within D Days challenge. It requires balancing constraints to find an optimal threshold.
Brute Force Approach for Capacity To Ship Packages Within D Days
The brute force approach involves checking every possible ship capacity starting from the smallest valid capacity and increasing it until we find one that satisfies the time constraint.
- Determine Bounds: The absolute minimum capacity must be equal to the heaviest package (otherwise, that package can never be loaded). The maximum necessary capacity is the sum of all weights (shipping everything in 1 day).
- Iterate: Start a loop from
max(weights)up tosum(weights). - Simulate: For each capacity
C, simulate the shipping process. Iterate through theweightsarray, accumulating weight into a "current day." Once the accumulated weight exceedsC, increment the day counter and start a new day. - Check: If the total days required is less than or equal to the input
days, returnCimmediately.
Pseudo-code
min_cap = max(weights)
max_cap = sum(weights)
for capacity from min_cap to max_cap:
days_needed = 1
current_load = 0
for w in weights:
if current_load + w > capacity:
days_needed += 1
current_load = 0
current_load += w
if days_needed <= days:
return capacityTime Complexity Analysis
The time complexity is , where is the number of packages and is the sum of all weights (representing the search space size). Since the sum of weights can be significantly larger than (up to ), this approach will result in a Time Limit Exceeded (TLE) error. The search space is too large to traverse linearly.
Algorithm Strategy: Binary Search Patterns
We implement the optimal solution using the Binary Search - On Answer pattern.
- Initialize Pointers: Set
leftto the maximum element inweightsandrightto the sum of elements inweights. - Binary Search Loop: While
left < right:- Calculate the midpoint:
mid = left + (right - left) / 2. - Evaluate
feasible(mid). - If True: This capacity works. It might be the minimal capacity, or there might be a smaller valid one. We record
midas a potential answer by settingright = mid. - If False: This capacity is too small. We need a larger capacity, so we set
left = mid + 1.
- Calculate the midpoint:
- Return Result: When the loop terminates (
left == right),leftrepresents the minimum feasible capacity.
The Feasibility Check (Greedy Approach)
To check if a specific capacity works:
- Initialize
days_needed = 1andcurrent_load = 0. - Iterate through
weights. - Add the current package weight to
current_load. - If
current_loadexceedscapacity, it means the current package cannot fit in the current day. We must:- Increment
days_needed. - Reset
current_loadto the weight of the current package (starting a new day).
- Increment
- If
days_neededexceeds the alloweddays, returnFalse. - Otherwise, return
True.
Execution Flow
Consider weights = [1, 2, 3, 4, 5], days = 3.
-
Initialization:
left= 5 (max weight)right= 15 (sum of weights)
-
Iteration 1:
mid= (5 + 15) // 2 = 10.- Check
feasible(10):- Day 1: 1+2+3+4 = 10 (Full).
- Day 2: 5.
- Total days: 2. Since 2 <= 3, returns
True.
- Logic: 10 works, try smaller.
right= 10.
-
Iteration 2:
left= 5,right= 10.mid= (5 + 10) // 2 = 7.- Check
feasible(7):- Day 1: 1+2+3 = 6. (Adding 4 would exceed 7).
- Day 2: 4. (Adding 5 would exceed 7).
- Day 3: 5.
- Total days: 3. Since 3 <= 3, returns
True.
- Logic: 7 works, try smaller.
right= 7.
-
Iteration 3:
left= 5,right= 7.mid= (5 + 7) // 2 = 6.- Check
feasible(6):- Day 1: 1+2+3 = 6.
- Day 2: 4.
- Day 3: 5.
- Total days: 3. Since 3 <= 3, returns
True.
- Logic: 6 works, try smaller.
right= 6.
-
Iteration 4:
left= 5,right= 6.mid= (5 + 6) // 2 = 5.- Check
feasible(5):- Day 1: 1+2 = 3. (Adding 3 exceeds 5).
- Day 2: 3. (Adding 4 exceeds 5).
- Day 3: 4. (Adding 5 exceeds 5).
- Day 4: 5.
- Total days: 4. Since 4 > 3, returns
False.
- Logic: 5 is too small.
left= 6.
-
Termination:
leftis 6,rightis 6. Loop ends.- Return
left(6).
Proof of Correctness
The algorithm relies on the monotonicity of the problem. Let be a boolean function indicating if capacity is valid.
- Invariant: The optimal solution always lies within the interval
[left, right]. - Initialization: We know the answer must be at least
max(weights)and at mostsum(weights). - Maintenance:
- If
midis valid ( is true), thenmidcould be the answer, or the answer is smaller. We reduce the range to[left, mid]. The answer is still in range. - If
midis invalid ( is false), thenmidand anything smaller is also invalid. We reduce the range to[mid + 1, right]. The answer is still in range.
- If
- Termination: The range shrinks by half at each step. When
left == right, the search space has converged to the single smallest valid capacity.
Pattern Reuse Notes
The Binary Search on Answer pattern is a powerful technique for optimization problems where the solution space is ordered.
- LeetCode 410: Split Array Largest Sum: Identical logic. Instead of "days", you split into "m subarrays". You minimize the largest sum among these subarrays.
- LeetCode 774: Minimize Max Distance to Gas Station: Uses binary search on floating-point numbers to find the minimum possible penalty (distance).
- LeetCode 875: Koko Eating Bananas: Finds the minimum eating speed (capacity) to finish bananas within
hhours. - LeetCode 1011: Capacity To Ship Packages Within D Days: The problem discussed here.
These problems all share the structure: "Find the minimum value such that a condition is true," where is monotonic.
Feynman coach · Before you peek at the code
Can you explain the core insight in your own words?
If you can explain it before reading code, you’re far more likely to recall it under interview pressure.
Reference Implementation
C++ Solution for LeetCode 1011
1#include <vector>
2#include <numeric>
3#include <algorithm>
4
5class Solution {
6public:
7 int shipWithinDays(std::vector<int>& weights, int days) {
8 // Initialize binary search bounds
9 int left = 0;
10 int right = 0;
11
12 for (int w : weights) {
13 left = std::max(left, w);
14 right += w;
15 }
16
17 while (left < right) {
18 int mid = left + (right - left) / 2;
19
20 if (canShip(weights, days, mid)) {
21 right = mid; // Try smaller capacity
22 } else {
23 left = mid + 1; // Increase capacity
24 }
25 }
26
27 return left;
28 }
29
30private:
31 bool canShip(const std::vector<int>& weights, int days, int capacity) {
32 int daysNeeded = 1;
33 int currentLoad = 0;
34
35 for (int w : weights) {
36 if (currentLoad + w > capacity) {
37 daysNeeded++;
38 currentLoad = 0;
39 }
40 currentLoad += w;
41 }
42
43 return daysNeeded <= days;
44 }
45};Java Solution for LeetCode 1011
1class Solution {
2 public int shipWithinDays(int[] weights, int days) {
3 int left = 0;
4 int right = 0;
5
6 // Determine bounds
7 for (int w : weights) {
8 left = Math.max(left, w);
9 right += w;
10 }
11
12 while (left < right) {
13 int mid = left + (right - left) / 2;
14
15 if (canShip(weights, days, mid)) {
16 right = mid; // Feasible, try to minimize
17 } else {
18 left = mid + 1; // Not feasible, increase capacity
19 }
20 }
21
22 return left;
23 }
24
25 private boolean canShip(int[] weights, int days, int capacity) {
26 int daysNeeded = 1;
27 int currentLoad = 0;
28
29 for (int w : weights) {
30 if (currentLoad + w > capacity) {
31 daysNeeded++;
32 currentLoad = 0;
33 }
34 currentLoad += w;
35 }
36
37 return daysNeeded <= days;
38 }
39}Python Solution for LeetCode 1011
1class Solution:
2 def shipWithinDays(self, weights: list[int], days: int) -> int:
3 def can_ship(capacity):
4 days_needed = 1
5 current_load = 0
6 for w in weights:
7 if current_load + w > capacity:
8 days_needed += 1
9 current_load = 0
10 current_load += w
11 return days_needed <= days
12
13 # Initialize bounds
14 left = max(weights)
15 right = sum(weights)
16
17 while left < right:
18 mid = left + (right - left) // 2
19 if can_ship(mid):
20 right = mid # Valid capacity, try smaller
21 else:
22 left = mid + 1 # Invalid, need larger capacity
23
24 return left