MediumNo. 1011
Capacity To Ship Packages Within D Days — LeetCode 1011 Python Solution
- Pattern
- Monotonic Stack
- Topics
- Array, Binary Search
- 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
- Time
- O(log n) or O(n log n)
- Space · auxiliary
- O(1)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0004 | Median of Two Sorted Arrays | Hard |
| 0033 | Search in Rotated Sorted Array | Medium |
| 0034 | Find First and Last Position of Element in Sorted Array | Medium |
| 0035 | Search Insert Position | Easy |
| 0074 | Search a 2D Matrix | Medium |
| 0081 | Search in Rotated Sorted Array II | Medium |
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.