1011. Capacity To Ship Packages Within D Days

Medium | Binary Search |

Source: LeetCode - Capacity To Ship Packages Within D Days GitHub: Solution / Performance

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]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.

Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.

Binary Search Problem Find a minimum capacity that can ship packages within certain days.

Boundary / Search Space

Left (Minimum) = MAX weights (cannot seperate a single package) Right (Maximum) = TOTAL weights

Condition

While Loop = Left < Right

Return Value

Left

class Solution:
    def shipWithinDays(self, weights: List[int], days: int) -> int:
        
        # ==================================================
        #  Binary Search                                   =
        # ==================================================
        # time  : O(nlog(m)), m is the search space
        # space : O(1)
        
        maxWeight, total = 0, 0
        for w in weights:
            total += w
            maxWeight = max(maxWeight, w)
        
        l, r = maxWeight, total
        while l < r:
            capacity = (l + r) // 2
            if self.valid(weights, days, capacity): r = capacity
            else: l = capacity + 1
            
        return l
    
    def valid(self, weights: List[int], D: int, capacity: int) -> bool:
        days, total = 1, 0
        for w in weights:
            total += w
            if total > capacity:
                total = w
                days += 1
                
                if days > D: return False
                
        return True

Last updated