LeetCode 875. Koko Eating Bananas
Today we're going to solve LeetCode 875. Koko Eating Bananas
| Problem description
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.
Examples:
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
| Concept
This is an interesting question. At first glance, I don't know how to solve it, and I am stuck on transforming the question into a reasonable algorithm. However, there's still a piece of important information we can consider:
Hint:
Eating speed decides how much time koko can eat all the bananas.
Therefore, we need to calculate koko can eat all bananas at what speed.
And a good way to prevent O(n) time complexity, is to use Binary Search
. You may ask, how about the range of time
?
Due to the constraint that koko cannot eat two different piles of bananas, we can define the maximum speed as the max elements in a pile
, thus preventing a useless counting process.
As for min speed needs to be at least one.
Now we get the algorithm to solve this problem!
| Analyzed complexity:
Time complexity: O(NLog(Max(Piles)))
Space complexity: O(1)
| Code
class Solution {
public:
int minEatingSpeed(vector<int>& piles, int h) {
int left = 1;
int right = *max_element(piles.begin(), piles.end());
while (left < right) {
int speed = left + (right - left) / 2;
if (canEat(piles, speed, h)) {
right = speed;
} else {
left = speed + 1;
}
}
return left;
}
bool canEat(vector<int>& piles, int speed, int& h) {
int min_eat_time = 0;
for (int pile : piles) {
min_eat_time += pile/speed;
if (pile%speed > 0) min_eat_time++;
}
return min_eat_time > h ? false : true;
}
};