File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments