LeetCode 1011. Capacity To Ship Packages Within D Days(python)

1011. Capacity To Ship Packages Within D Days

  1. Capacity To Ship Packages Within D Days python solution

题目描述

A conveyor belt has packages that must be shipped from one port to another within D days.

The i-th 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 D days.

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

解析

本题使用二分查找进行求解,船容量的下边界是 max(weights)
上边界是sum(weights)。那么船在D天内能完成任务所对应的值就应该在上下边界之间,所以我们在此区间内进行二分查找。

对于一个载重量,如果我们计算出的天数大于D,说明这个载重量偏小了,则更新下边界。
若计算出的天数小于D,说明我们可以用更小的载重量完成运输,则更新上边界。
直到上下边界相等时,结束查找

class Solution:
    def shipWithinDays(self, weights: List[int], D: int) -> int:
        left,right=max(weights),sum(weights)
        while left<right:
            mid,d,current_weight=(left+right)//2,1,0
            for w in weights:
                if w+current_weight>mid:
                    d+=1
                    current_weight=0
                current_weight+=w
            if d>D: left=mid+1
            else: right=mid
        return left
        

Reference

https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/256729/JavaC%2B%2BPython-Binary-Search

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值