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
class Solution {
// Helper function to find maximum pile value
public static int maxsum(int [] arr) {
int sum = 0;
for (int a : arr) {
sum = sum + a;
}
return sum;
}
public int minEatingSpeed(int[] piles, int h) {
int n = piles.length;
int start = 1; // Minimum eating speed can be 1 banana per hour
int end = 0; // We will find maximum pile value to set as the maximum possible eating speed
// Find the maximum value from piles
for (int pile : piles) {
end = Math.max(end, pile);
}
int ans = 0; // To store the minimum speed found
// Standard binary search
while (start <= end) {
int mid = start + (end - start) / 2; // Current speed to test
int hourcount = 0; // To count how many total hours needed at speed = mid
for (int i = 0; i < n; i++) {
// Each pile requires pile[i]/mid hours (rounded up)
hourcount += piles[i] / mid;
// If there is a remainder, we need one more hour
if (piles[i] % mid != 0) {
hourcount++;
}
}
// Now check if total hours needed is within h
if (hourcount > h) {
// Need more hours than allowed, so speed is too slow → increase speed
start = mid + 1;
} else {
// Speed is enough (or more), try to find smaller valid speed
ans = mid;
end = mid - 1;
}
}
return ans;
}
}
Comments
Post a Comment