forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKokoEatingBananas.java
More file actions
41 lines (33 loc) · 1.05 KB
/
KokoEatingBananas.java
File metadata and controls
41 lines (33 loc) · 1.05 KB
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
package binary_search;
/**
* Description: https://leetcode.com/problems/koko-eating-bananas
* Difficulty: Medium
* Time complexity: O(n log(Integer.MAX_VALUE))
* Space complexity: O(1)
*/
public class KokoEatingBananas {
public int minEatingSpeed(int[] piles, int hours) {
int minSpeed = 1;
int maxSpeed = Integer.MAX_VALUE;
int min = Integer.MAX_VALUE;
while (minSpeed <= maxSpeed) {
int midSpeed = minSpeed + (maxSpeed - minSpeed) / 2;
if (canEatAllBananas(piles, hours, midSpeed)) {
min = midSpeed;
maxSpeed = midSpeed - 1;
} else {
minSpeed = midSpeed + 1;
}
}
return min;
}
private boolean canEatAllBananas(int[] piles, int totalTime, int speed) {
int currentTime = 0;
for (int pile : piles) {
currentTime += pile / speed;
currentTime += pile % speed == 0 ? 0 : 1;
if (currentTime > totalTime) return false;
}
return true;
}
}