File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ package binarysearch ;
2
+
3
+ public class Problem875_KokoEatingBananas {
4
+
5
+ public int minEatingSpeed (int [] piles , int H ) {
6
+ // min(K) : eat all piles & times <= H
7
+ // [3,6,7,11]
8
+ // K = 11 -> 4 hours
9
+ // K = 8 -> 5 hours
10
+ // K = 6 -> 1 + 1 + 2 + 2 = 6 hours
11
+ // K = 5 -> 1 + 2 + 2 + 3 = 8 hours
12
+ // K = 4 -> 1 + 2 + 2 + 3 = 8 hours
13
+ // K = 3 -> 1 + 2 + 3 + 4 > 8 hours
14
+
15
+ // lo = 1, hi = max;
16
+ // function(mid) <= H --> hi = mid-1
17
+ // function(mid) > H --> lo = mid+1
18
+ // return lo
19
+
20
+ int lo = 1 , hi = 0 ;
21
+ for (int pile : piles ) hi = Math .max (hi , pile );
22
+
23
+ while (lo <= hi ) {
24
+ int mid = lo + (hi -lo )/2 ;
25
+ if (timeToEatAll (piles , mid ) <= H ) hi = mid -1 ;
26
+ else lo = mid +1 ;
27
+ }
28
+ return lo ;
29
+ }
30
+
31
+ private int timeToEatAll (int [] piles , int speed ) {
32
+ int res = 0 ;
33
+ for (int pile : piles ) {
34
+ if (speed >= pile ) res += 1 ;
35
+ else {
36
+ res += pile /speed ;
37
+ if (pile %speed != 0 ) res ++;
38
+ }
39
+ }
40
+ return res ;
41
+ }
42
+ }
You can’t perform that action at this time.
0 commit comments