-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path875.koko-eating-bananas.py
59 lines (49 loc) · 1.14 KB
/
875.koko-eating-bananas.py
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Level: Medium
# TAGS: Array, Binary Search
from typing import List
import math
class Solution:
# Time: O(N*log(M)) w/ M = max(piles) | Space: O(1)
def minEatingSpeed(self, piles: List[int], h: int) -> int:
def can_finish(k):
total = 0
for pile in piles:
total += math.ceil(pile / k)
return total <= h
total = sum(piles)
lo, hi = math.ceil(total / h), max(piles)
while lo < hi:
# This is the second way to find the mid to prevent overflow
mid = lo + (hi - lo) // 2
if can_finish(mid):
hi = mid
else:
lo = mid + 1
return lo
solution = Solution().minEatingSpeed
print("4", solution([3, 6, 7, 11], 8))
print("30", solution([30, 11, 23, 4, 20], 5))
print("23", solution([30, 11, 23, 4, 20], 6))
tests = [
(
(
[3, 6, 7, 11],
8,
),
4,
),
(
(
[30, 11, 23, 4, 20],
5,
),
30,
),
(
(
[30, 11, 23, 4, 20],
6,
),
23,
),
]