Capacity To Ship Packages Within D Days — LeetCode 1011 Python Solution
- Problem
- #1011
- Pattern
- Monotonic Stack
- Reading time
- 3 min
- Source
- leetcode.com
The problem
A conveyor belt has packages that must be shipped from one port to another within days days. The ith package on the conveyor belt has a weight of weights[i].
Example
- Input
- weights = [1,2,3,4,5,6,7,8,9,10], days = 5
- Output
- 15
- Explanation
- A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
Python solution
class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def check(mx):
ws, cnt = 0, 1
for w in weights:
ws += w
if ws > mx:
cnt += 1
ws = w
return cnt <= days
left, right = max(weights), sum(weights) + 1
return left + bisect_left(range(left, right), True, key=check)Complexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 1011. Capacity To Ship Packages Within D Days is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1011. Capacity To Ship Packages Within D Days?
- LeetCode 1011. Capacity To Ship Packages Within D Days is rated Medium on LeetCode.
- What topics does LeetCode 1011. Capacity To Ship Packages Within D Days cover?
- LeetCode 1011. Capacity To Ship Packages Within D Days is tagged Array and Binary Search on LeetCode.