题目
传送带上的包裹必须在
days
天内从一个港口运送到另一个港口。传送带上的第
i
个包裹的重量为weights[i]
。每一天,我们都会按给出重量(weights
)的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。返回能在
days
天内将传送带上的所有包裹送达的船的最低运载能力。
解题
def can_ship_in_days(weights, capacity, days):
current_load = 0
days_needed = 1
for weight in weights:
if current_load + weight > capacity:
days_needed += 1
current_load = 0
current_load += weight
if days_needed > days:
return False
return True
def shipWithinDays(weights, days):
left = max(weights)
right = sum(weights)
while left < right:
mid = (left + right) // 2
if can_ship_in_days(weights, mid, days):
right = mid
else:
left = mid + 1
return left
# 示例输入
weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
days = 5
# 输出
print(shipWithinDays(weights, days)) # 输出: 15