Capacity To Ship Packages Within D Days
franklinqin0 ArrayBinary Search
# Solution
# Binary Search
from math import ceil
class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def ok(capacity):
# num days needed
res = 0
temp = 0
for weight in weights:
if temp + weight <= capacity:
temp += weight
else:
res += 1
temp = weight
return res < days
right = sum(weights)
left = max(ceil(right/days), max(weights))
# binary search
while left <= right:
mid = left + (right - left) // 2
if ok(mid):
right = mid - 1
else:
left = mid + 1
# return mid
return mid if ok(mid) else mid+1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28