Leetcode-1011. Capacity to Ship Packages Within D Days

Original link: https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/

Inspired by Hint: Binary search on the answer. We need a function possible(capacity) which returns true if and only if we can do the task in D days.

Implement a method to see if a combination of weights, capacity and day can meet the requirement.

Code:

    def is_time_enough(self, weights, load, day):
        
        cur = 0
        
        for i in weights:
            
            cur += i    
            
            if cur > load:
                cur = i
                day -= 1
            if day <= 0 or load < i:
                return False
        return True if day >= 1 else False

Then implement a binary search.

For this question, people use the same strategy (slide window) to implement “is_time_enough”, so we must choose a suitable search range to achieve a high rank.

Here’s how I choose the search range:

Code:

class Solution(object):
    def shipWithinDays(self, weights, D):
        """
        :type weights: List[int]
        :type D: int
        :rtype: int
        """
        
        hi = max(weights)
        lo = hi // 2
        
        while self.is_time_enough(weights, hi, D) == False:
            hi *= 2
            lo *= 2
        
        pointer = (lo + hi)//2
        
        while hi - lo > 1:
            if self.if_time_enough(weights, pointer, D) == True:
                hi = pointer
                pointer = (lo + hi) // 2
            else:
                lo = pointer
                pointer = (lo + hi) // 2
                
        if self.is_time_enough(weights, pointer, D) == False:
            return pointer + 1
        return pointer
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值