Skip to content

Commit 84aaa68

Browse files
Create 875-Koko-Eating-Bananas.java
1 parent 7e1ca04 commit 84aaa68

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

java/875-Koko-Eating-Bananas.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public int minEatingSpeed(int[] piles, int h) {
3+
// Initalize the left and right boundaries
4+
int left = 1, right = 1;
5+
for (int pile : piles) {
6+
right = Math.max(right, pile);
7+
}
8+
9+
while (left < right) {
10+
// Get the middle index between left and right boundary indexes.
11+
// hourSpent stands for the total hour Koko spends.
12+
int middle = (left + right) / 2;
13+
int hourSpent = 0;
14+
15+
// Iterate over the piles and calculate hourSpent.
16+
// We increase the hourSpent by ceil(pile / middle)
17+
for (int pile : piles) {
18+
hourSpent += Math.ceil((double) pile / middle);
19+
}
20+
21+
// Check if middle is a workable speed, and cut the search space by half.
22+
if (hourSpent <= h) {
23+
right = middle;
24+
} else {
25+
left = middle + 1;
26+
}
27+
}
28+
29+
// Once the left and right boundaries coincide, we find the target value,
30+
// that is, the minimum workable eating speed.
31+
return right;
32+
}
33+
}

0 commit comments

Comments
 (0)