Capacity To Ship Packages Within D Days
Problem
Given an array weights representing the weights of packages and an integer days, return the least weight capacity of a ship that will result in all the packages being shipped within days days.
- 1 ≤ days ≤ weights.length ≤ 5 * 10⁴
- 1 ≤ weights[i] ≤ 500
Example
weights = [1,2,3,4,5,6,7,8,9,10], days = 515A brute-force approach would try every capacity from the heaviest package (10) up to the sum of all weights (55), checking if the packages can be shipped within 5 days. For capacity 15, the ship can load packages as follows: Day 1: [1,2,3,4,5], total 15; Day 2: [6,7], total 13; Day 3: [8], total 8; Day 4: [9], total 9; Day 5: [10], total 10. This is the minimal capacity that allows shipping within 5 days.
Approach
Straightforward Solution
A brute-force approach tries every capacity from max(weights) to sum(weights), simulating the shipping process for each capacity. This approach is O(n * sum(weights)) and is too slow for large inputs.
Core Observation
The minimal ship capacity must be at least the heaviest package and at most the sum of all package weights. The problem reduces to finding the smallest capacity in this range that allows shipping within the given days.
Path to Optimal
Recognizing that the feasibility of shipping within days is a monotonic predicate with respect to capacity allows the use of binary search. If a capacity can ship within days, any larger capacity can also ship within days. If it cannot, any smaller capacity also cannot. This monotonicity enables efficient search for the minimal feasible capacity.
Optimal Approach
Use binary search between max(weights) and sum(weights). For each mid capacity, simulate shipping by accumulating package weights until exceeding capacity, then increment day count. If the total days used is within the allowed days, move the right boundary to mid; otherwise, move the left boundary to mid + 1. Return the left boundary after convergence.
Time
O(n log S)
Where n is the number of packages and S is the sum of weights. Each binary search iteration takes O(n) to simulate shipping, and the search space is at most sum(weights), leading to O(log S) iterations.
Space
O(1)
Only a few variables are used for counters and boundaries; no additional data structures proportional to input size are needed.
Pattern Spotlight
Binary Search on Answer Space (Feasibility Check)
When the problem asks for a minimal or maximal value satisfying a monotonic feasibility condition, use binary search on the answer space by defining a predicate that checks feasibility and narrowing the search range accordingly.
Solution
| 1 | class Solution: |
| 2 | def shipWithinDays(self, weights: List[int], days: int) -> int: |
| 3 | def canShip(capacity): |
| 4 | used_days = 1 |
| 5 | curr_weight = 0 |
| 6 | |
| 7 | for weight in weights: |
| 8 | if curr_weight + weight > capacity: |
| 9 | used_days += 1 |
| 10 | curr_weight = 0 |
| 11 | |
| 12 | curr_weight += weight |
| 13 | |
| 14 | return used_days <= days |
| 15 | |
| 16 | l, r = max(weights), sum(weights) |
| 17 | |
| 18 | while l < r: |
| 19 | capacity = (l + r) // 2 |
| 20 | |
| 21 | if canShip(capacity): |
| 22 | r = capacity |
| 23 | else: |
| 24 | l = capacity + 1 |
| 25 | |
| 26 | return l |
| 1 | import java.util.List; |
| 2 | |
| 3 | public class Solution { |
| 4 | public int shipWithinDays(List<Integer> weights, int days) { |
| 5 | int l = 0, r = 0; |
| 6 | for (int w : weights) { |
| 7 | l = Math.max(l, w); |
| 8 | r += w; |
| 9 | } |
| 10 | |
| 11 | while (l < r) { |
| 12 | int capacity = l + (r - l) / 2; |
| 13 | if (canShip(weights, days, capacity)) { |
| 14 | r = capacity; |
| 15 | } else { |
| 16 | l = capacity + 1; |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | return l; |
| 21 | } |
| 22 | |
| 23 | private boolean canShip(List<Integer> weights, int days, int capacity) { |
| 24 | int usedDays = 1; |
| 25 | int currWeight = 0; |
| 26 | |
| 27 | for (int weight : weights) { |
| 28 | if (currWeight + weight > capacity) { |
| 29 | usedDays++; |
| 30 | currWeight = 0; |
| 31 | } |
| 32 | currWeight += weight; |
| 33 | } |
| 34 | |
| 35 | return usedDays <= days; |
| 36 | } |
| 37 | } |
| 1 | #include <vector> |
| 2 | #include <algorithm> |
| 3 | |
| 4 | using namespace std; |
| 5 | |
| 6 | class Solution { |
| 7 | public: |
| 8 | int shipWithinDays(vector<int>& weights, int days) { |
| 9 | int l = 0, r = 0; |
| 10 | for (int w : weights) { |
| 11 | l = max(l, w); |
| 12 | r += w; |
| 13 | } |
| 14 | |
| 15 | while (l < r) { |
| 16 | int capacity = l + (r - l) / 2; |
| 17 | if (canShip(weights, days, capacity)) { |
| 18 | r = capacity; |
| 19 | } else { |
| 20 | l = capacity + 1; |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | return l; |
| 25 | } |
| 26 | |
| 27 | private: |
| 28 | bool canShip(const vector<int>& weights, int days, int capacity) { |
| 29 | int usedDays = 1; |
| 30 | int currWeight = 0; |
| 31 | |
| 32 | for (int weight : weights) { |
| 33 | if (currWeight + weight > capacity) { |
| 34 | usedDays++; |
| 35 | currWeight = 0; |
| 36 | } |
| 37 | currWeight += weight; |
| 38 | } |
| 39 | |
| 40 | return usedDays <= days; |
| 41 | } |
| 42 | }; |
| 1 | var shipWithinDays = function(weights, days) { |
| 2 | let l = 0, r = 0; |
| 3 | for (const w of weights) { |
| 4 | l = Math.max(l, w); |
| 5 | r += w; |
| 6 | } |
| 7 | |
| 8 | function canShip(capacity) { |
| 9 | let usedDays = 1; |
| 10 | let currWeight = 0; |
| 11 | |
| 12 | for (const weight of weights) { |
| 13 | if (currWeight + weight > capacity) { |
| 14 | usedDays++; |
| 15 | currWeight = 0; |
| 16 | } |
| 17 | currWeight += weight; |
| 18 | } |
| 19 | |
| 20 | return usedDays <= days; |
| 21 | } |
| 22 | |
| 23 | while (l < r) { |
| 24 | const capacity = Math.floor((l + r) / 2); |
| 25 | if (canShip(capacity)) { |
| 26 | r = capacity; |
| 27 | } else { |
| 28 | l = capacity + 1; |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | return l; |
| 33 | }; |
Step-by-Step Solution
Simulate Shipping to Check Feasibility of Capacity
| 3 | def canShip(capacity): |
| 4 | used_days = 1 |
| 5 | curr_weight = 0 |
| 7 | for weight in weights: |
| 8 | if curr_weight + weight > capacity: |
| 9 | used_days += 1 |
| 10 | curr_weight = 0 |
| 12 | curr_weight += weight |
| 14 | return used_days <= days |
Objective
To determine if all packages can be shipped within the given days using a specified ship capacity.
Key Insight
By iterating through the package weights and accumulating them until the capacity is exceeded, the algorithm counts how many days are needed to ship all packages. This simulation directly tests the feasibility predicate required for binary search. It leverages the problem's sequential loading constraint and ensures that the capacity is respected daily.
Interview Quick-Check
Core Logic
The simulation accumulates package weights until exceeding capacity, then increments the day count and resets the current load, effectively partitioning packages into days.
State & Boundaries
Initialize used_days to 1 and curr_weight to 0 to represent the first day and current load.
Common Pitfalls & Bugs
Forgetting to reset curr_weight after incrementing used_days leads to incorrect day counts.
Apply Binary Search to Find Minimal Feasible Capacity
| 16 | l, r = max(weights), sum(weights) |
| 18 | while l < r: |
| 19 | capacity = (l + r) // 2 |
| 21 | if canShip(capacity): |
| 22 | r = capacity |
| 23 | else: |
| 24 | l = capacity + 1 |
| 26 | return l |
Objective
To efficiently narrow down the minimal ship capacity that allows shipping within the given days using binary search.
Key Insight
The search space is bounded by the heaviest package and the sum of all weights. By repeatedly checking the feasibility of the midpoint capacity and adjusting the search boundaries accordingly, the algorithm converges to the minimal capacity. This approach exploits the monotonicity of the feasibility predicate and avoids exhaustive search.
Interview Quick-Check
Core Logic
Binary search adjusts the search boundaries based on the feasibility check: if capacity is sufficient, search left half; otherwise, search right half.
State & Boundaries
The loop continues while left < right, ensuring convergence to the minimal feasible capacity.
Common Pitfalls & Bugs
Incorrectly updating boundaries (e.g., not adding 1 when capacity is insufficient) can cause infinite loops or incorrect results.
Line Analysis
This solution has 5 Critical lines interviewers watch for.
return used_days <= days
Return whether the total days used is within the allowed days.
This boolean result serves as the feasibility predicate for binary search, determining if the capacity is sufficient.
return l
Return the minimal capacity found after binary search completes.
At loop termination, left equals the minimal feasible capacity, which is the problem's solution.
if curr_weight + weight > capacity:
Check if adding the current package exceeds the capacity.
This condition detects when the current day's load would surpass the ship's capacity, triggering a day increment.
used_days += 1
Increment the day count when capacity is exceeded.
Increasing the day count reflects starting a new shipping day due to capacity overflow, critical for feasibility calculation.
if canShip(capacity):
Check if shipping is feasible with the current midpoint capacity.
This check guides the binary search direction by testing the feasibility predicate.
curr_weight = 0
Reset the current weight to zero for the new day.
Resetting current weight ensures the new day's load starts fresh, preventing carryover from previous day.
l, r = max(weights), sum(weights)
Initialize the binary search boundaries: left as max package weight, right as sum of all weights.
Setting boundaries to these values ensures the search space includes all feasible capacities, with left as the minimal possible capacity and right as the maximal.
r = capacity
If feasible, move the right boundary to the midpoint to search for smaller capacity.
Reducing the right boundary narrows the search to smaller capacities that might still be feasible, aiming for minimal capacity.
else:
If not feasible, move the left boundary to midpoint plus one to search larger capacities.
Increasing the left boundary excludes insufficient capacities, ensuring eventual convergence to a feasible solution.
used_days = 1
Initialize the count of days used to 1.
Starting with one day assumes shipping begins immediately, and days increment only when capacity is exceeded.
curr_weight = 0
Initialize the current weight loaded on the ship to 0.
This variable tracks the cumulative weight loaded on the current day, essential for capacity checks.
curr_weight += weight
Add the current package weight to the current day's load.
Accumulate package weights to simulate loading until capacity is reached or exceeded.
while l < r:
Continue binary search while left boundary is less than right.
This loop condition ensures the search space shrinks until the minimal feasible capacity is found.
capacity = (l + r) // 2
Calculate the midpoint capacity between left and right.
Midpoint selection divides the search space, enabling logarithmic convergence.
def canShip(capacity):
Define a helper function to check if shipping is possible with a given capacity.
Encapsulating the feasibility check as a helper function isolates the logic needed for binary search, improving code clarity and reusability.
for weight in weights:
Iterate over each package weight in order.
Sequential iteration respects the problem constraint that packages must be shipped in order without reordering.
l = capacity + 1
Continue the binary search loop with updated boundaries.
This iteration progressively narrows the search space until left equals right.
Test Your Understanding
Why is binary search applicable on the capacity range, and how does the feasibility check ensure correctness?
Because the feasibility of shipping all packages within the given days is monotonic with respect to capacity: if a capacity can ship within days, all larger capacities can too; if it cannot, all smaller capacities cannot. This monotonicity allows binary search to efficiently find the minimal capacity that satisfies the condition.
Related Problems
Binary Search pattern
Don't just read it. Drill it.
Reconstruct Capacity To Ship Packages Within D Days from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Capacity To Ship Packages Within D Days drill