Capacity To Ship Packages Within D Days - Problem
Shipping Problem: You're managing a shipping company that needs to transport packages from port A to port B. You have a conveyor belt with packages that must be shipped within a specific time frame.
Given an array
Key Rules:
Goal: Find the least weight capacity that allows all packages to be shipped within the time constraint.
Given an array
weights where weights[i] represents the weight of the i-th package, and an integer days representing the maximum days allowed for shipping, you need to determine the minimum weight capacity of the ship required to transport all packages within the given time limit.Key Rules:
- Packages must be loaded in order from the conveyor belt
- You cannot exceed the ship's weight capacity on any given day
- All packages must be shipped within
daysdays
Goal: Find the least weight capacity that allows all packages to be shipped within the time constraint.
Input & Output
example_1.py โ Basic Case
$
Input:
weights = [1,2,3,4,5,6,7,8,9,10], days = 5
โบ
Output:
15
๐ก Note:
A ship capacity of 15 is sufficient: Day 1: [1,2,3,4,5] = 15kg, Day 2: [6,7] = 13kg, Day 3: [8] = 8kg, Day 4: [9] = 9kg, Day 5: [10] = 10kg. All packages are shipped within 5 days.
example_2.py โ Tight Constraint
$
Input:
weights = [3,2,2,4,1,4], days = 3
โบ
Output:
6
๐ก Note:
A ship capacity of 6 works: Day 1: [3,2] = 5kg, Day 2: [2,4] = 6kg, Day 3: [1,4] = 5kg. Capacity 5 would fail because [2,4] = 6kg exceeds the limit.
example_3.py โ Single Day
$
Input:
weights = [1,2,3,1,1], days = 1
โบ
Output:
8
๐ก Note:
All packages must be shipped in one day, so the ship needs capacity equal to the sum of all weights: 1+2+3+1+1 = 8kg.
Visualization
Tap to expand
Understanding the Visualization
1
Start Day 1
Begin loading packages in order until capacity reached
2
Capacity Check
If next package exceeds capacity, start a new day
3
Continue Loading
Repeat process until all packages are loaded
4
Validate Timeline
Check if total days used is within the allowed limit
Key Takeaway
๐ฏ Key Insight: The monotonic property (if capacity X works, then capacity > X works) allows us to use binary search instead of testing every possible capacity value, reducing time complexity from O(n ร sum) to O(n ร log(sum)).
Time & Space Complexity
Time Complexity
O(n ร log(sum))
Binary search runs log(sum) iterations, each requiring O(n) simulation of package loading
โก Linearithmic
Space Complexity
O(1)
Only using a few variables for binary search bounds and simulation
โ Linear Space
Constraints
- 1 โค days โค weights.length โค 5 ร 104
- 1 โค weights[i] โค 500
- Packages must be shipped in the given order
- Ship capacity must be at least the weight of the heaviest package
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code