875. Koko Eating Bananas(Solution || Leetcode medium || Java)

Palakkgoyal
2 min readNov 5, 2022

--

Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.

Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.

Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.

Return the minimum integer k such that she can eat all the bananas within h hours.

Example 1:

Input: piles = [3,6,7,11], h = 8
Output: 4

Example 2:

Input: piles = [30,11,23,4,20], h = 5
Output: 30

Example 3:

Input: piles = [30,11,23,4,20], h = 6
Output: 23

Constraints:

  • 1 <= piles.length <= 104
  • piles.length <= h <= 109
  • 1 <= piles[i] <= 109

SOLUTION:

class Solution {
public int minEatingSpeed(int[] piles, int h) {
//Find the max element from the arry which will give us our upper limit of binary search
int hi = Arrays.stream(piles).max().getAsInt();

//As eating bananas can’t be negative or 0, it give our lower limit of binary search as 0
int lo = 1;

while(lo < hi){//applying binary search
int mid = lo + (hi — lo)/2;

//if koko is taking more time to eat bananas than given hours that are h, so will increse our lower value
if(!ateAll(piles,h,mid)){
lo = mid + 1;
}
else{
hi = mid;
}
}
return lo;
}

//function to check whether at the present value of mid, can koko eat all the bananas
public boolean ateAll(int[] piles, int h, int mid){
int count = 0;

for(int pile: piles){//adding all the hours that she will take to eat bananas at present speed that is mid
count += pile/mid;
if(pile% mid != 0){
count++;
}
}

return (count <= h);
}
}

Thank you for reading. If you have any queries then, please let me know in the comment section, I will surely be responsive toward it.

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet