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