-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0875-koko-eating-bananas.java
34 lines (29 loc) · 1.11 KB
/
0875-koko-eating-bananas.java
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
class Solution {
public int minEatingSpeed(int[] piles, int h) {
// Initalize the left and right boundaries
int left = 1, right = 1;
for (int pile : piles) {
right = Math.max(right, pile);
}
while (left < right) {
// Get the middle index between left and right boundary indexes.
// hourSpent stands for the total hour Koko spends.
int middle = (left + right) / 2;
int hourSpent = 0;
// Iterate over the piles and calculate hourSpent.
// We increase the hourSpent by ceil(pile / middle)
for (int pile : piles) {
hourSpent += Math.ceil((double) pile / middle);
}
// Check if middle is a workable speed, and cut the search space by half.
if (hourSpent <= h) {
right = middle;
} else {
left = middle + 1;
}
}
// Once the left and right boundaries coincide, we find the target value,
// that is, the minimum workable eating speed.
return right;
}
}