1011. 在 D 天内送达包裹的能力 -- 巧用二分搜索

1011. 在 D 天内送达包裹的能力


class ShipWithinDays:
    """
    1011. 在 D 天内送达包裹的能力
    巧用二分搜索
    https://leetcode.cn/problems/capacity-to-ship-packages-within-d-days/description/
    """
    def solution(self, weights: List[int], days: int) -> int:
        left, right = max(weights), sum(weights)
        while left < right:
            mid = left + (right - left) // 2
            if self.f(weights, mid) <= days:
                right = mid
            else:
                left = mid + 1

        return left

    # 定义:当运载能力为 x 时,需要 f(x) 天运完所有货物
    # f(x) 随着 x 的增加单调递减
    def f(self, weights, x):
        days = 0
        i = 0
        while i < len(weights):
            # 尽可能多装货物
            cap = x
            while i < len(weights):
                if cap < weights[i]:
                    break
                else:
                    cap -= weights[i]
                    i += 1
            days += 1

        return days

你可能感兴趣的:(LeetCode,数据结构与算法,二分搜索)