-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathKokoEatingBananas.java
More file actions
64 lines (57 loc) · 1.28 KB
/
KokoEatingBananas.java
File metadata and controls
64 lines (57 loc) · 1.28 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution {
public int minEatingSpeed(int[] piles, int H) {
long low = 1;
long high = piles[0];
for(int pile: piles){
high = Math.max(high, pile);
}
while(low<high){
long mid = low + (high-low)/2;
if(!isPossibleToEatAll(piles, H, mid)){
low = mid + 1;
} else{
high =mid;
}
}
return (int)low;
}
private boolean isPossibleToEatAll(int[] piles, int hours,long currK){
long count =0;
for(long pile: piles){
count += pile/currK;
if(pile%currK!=0){
count++;
}
}
return (count<=hours);
}
}
// Koko-Eating-Bananas
// TC : O(nlogn)
class Solution {
public int minEatingSpeed(int[] piles, int h) {
int l = piles.length;
Arrays.sort(piles);
if (l == h)
return piles[l-1];
int low = 1;
int high = piles[l-1];
// apply binary search
while (low <= high) {
int mid = (low + high) / 2;
int cnt = count(piles, mid);
if (cnt <= h)
high = mid-1;
else
low = mid+1;
}
return low;
}
private int count(int [] piles, int max) {
int res = 0;
for (int pile : piles) {
res += (Math.ceil((double)pile/max));
}
return res;
}
}