1011. Capacity To Ship Packages Within D Days
Medium | Binary Search |
Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
Output: 15
Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given,
so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
# ==================================================
# Binary Search =
# ==================================================
# time : O(nlog(m)), m is the search space
# space : O(1)
maxWeight, total = 0, 0
for w in weights:
total += w
maxWeight = max(maxWeight, w)
l, r = maxWeight, total
while l < r:
capacity = (l + r) // 2
if self.valid(weights, days, capacity): r = capacity
else: l = capacity + 1
return l
def valid(self, weights: List[int], D: int, capacity: int) -> bool:
days, total = 1, 0
for w in weights:
total += w
if total > capacity:
total = w
days += 1
if days > D: return False
return TrueLast updated