Capacity To Ship Packages Within D Days — LeetCode 1011 Python Solution

MediumArrayBinary Search
Problem
#1011
Reading time
3 min

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

Python
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

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview