875. Koko Eating Bananas
a famous binary search problem.
1class Solution:
2 def minEatingSpeed(self, piles: List[int], h: int) -> int:
3
4 l = 1
5 r = max(piles) # 10**9 - 1 also works, but you don’t need to eat faster than the largest pile
6
7 # bisect_left since we want the minimum speed
8 while l <= r:
9 speed = (l + r) // 2
10
11 duration = 0
12 for pile in piles:
13 duration += -(-pile // speed) # math.ceil() equivalent
14 if duration > h: # early break saves a bit of time on longer piles lists
15 break
16
17 if duration <= h: # if condition satisfies
18 r = speed - 1 # we try a smaller one (bisect_left shrinks r; bisect_right bumps l)
19 else:
20 l = speed + 1
21
22 return l # l for bisect_left, r for bisect_right
#Neetcode150 #Binary-Search #Python