LeetCode 1011. Capacity To Ship Packages Within D Days 二分答案
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.
Solution
直接二分答案,也就是天数,然后找到最小可行的 \(capacity\)
点击查看代码
class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def check(weights, cand):
days = 0
i = 0
while i<len(weights):
cap = cand
while i<len(weights):
if cap<weights[i]:
break
else:
cap = cap-weights[i]
i+=1
days+=1
return days
left = 1
right = 0
for w in weights:
left = max(left, w)
right += w
while left<=right:
mid = left+int((right-left)/2)
if check(weights, mid)<=days:
right = mid-1
else:
left=mid+1
return left