LeetCode 875: Koko Eating Bananas
Problem Description
Explanation
To solve this problem, we can use binary search to find the minimum integer k such that Koko can eat all the bananas within h hours. We will consider the range of possible values for k between 1 and the maximum number of bananas in the piles. For each value of k, we will calculate the total hours needed to eat all the bananas. If the total hours needed is less than or equal to h, we will update our search space to the left half; otherwise, we will update our search space to the right half.
Algorithm:
- Initialize left = 1 and right = maximum number of bananas in the piles.
- Perform binary search to find the minimum k such that Koko can eat all the bananas within h hours.
- Within the binary search loop, calculate the total hours needed for the current value of k by iterating through all piles and adding up the hours needed to eat each pile.
- Update the search space based on the total hours needed.
- Return the minimum k found.
Time Complexity: O(n log m), where n is the number of piles and m is the maximum number of bananas in the piles.
Space Complexity: O(1)
Solutions
class Solution {
public int minEatingSpeed(int[] piles, int h) {
int left = 1;
int right = Arrays.stream(piles).max().getAsInt();
while (left < right) {
int mid = left + (right - left) / 2;
int hours = 0;
for (int pile : piles) {
hours += (pile + mid - 1) / mid;
}
if (hours <= h) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
Related LeetCode Problems
Loading editor...