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

发布了131 篇原创文章 · 获赞 6 · 访问量 6919

猜你喜欢

转载自blog.csdn.net/Orientliu96/article/details/104260350