二分搜索(2)-在 D 天内送达包裹的能力

105 阅读1分钟

题目

在 D 天内送达包裹的能力

思路

搜索区间为[left,right][left, right],初始left=max(weights)left=max(weights)right=sum(weights)right=sum(weights)

  • 能运送完,下一搜索区间[left,mid1][left, mid-1]
  • 不能送完,下一搜索区间[mid+1,right][mid+1, right]

代码

class Solution:
    def shipWithinDays(self, weights: List[int], days: int) -> int:

        def can_finish(w):
            cnt = 0
            temp = 0
            for weight in weights:
                temp += weight
                if temp > w:
                    temp = weight
                    cnt += 1
            if temp:
                cnt += 1
            return cnt <= days

        left = max(weights)
        right = sum(weights)

        while left <= right:
            mid = left + (right - left) // 2
            if can_finish(mid):
                right = mid - 1
            else:
                left = mid + 1
        return left