Leetcode 1056 Solution

This article provides solution to leetcode question 1056 (capacity-to-ship-packages-within-d-days)

https://leetcode.com/problems/capacity-to-ship-packages-within-d-days

Solution

class Solution:
    def check(self, weights, D, ship):
        c = 0
        left = 0
        for weight in weights:
            if weight > left:
                c += 1
                left = ship

                if c > D:
                    return False

                if weight > left:
                    return False

            left -= weight

        return c <= D

    def shipWithinDays(self, weights: List[int], D: int) -> int:
        l = 1
        r = sum(weights)

        while l < r:
            m = (l + r) // 2

            if self.check(weights, D, m):
                r = m
            else:
                l = m + 1

        return l