Problem
Koko loves to eat bananas.Ā There areĀ NĀ piles of bananas, theĀ i-thĀ 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 won’t eat any more bananas during this hour.
Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back.
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
Note:
1 <= piles.length <= 10^4piles.length <= H <= 10^91 <= piles[i] <= 10^9
Solution: Binary Search
search for the smallest k [1, max_pile_height] such that eating time h <= H.
Time complexity: O(nlogh)
Space complexity: O(1)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua // Running time: 48 ms class Solution { public: int minEatingSpeed(vector<int>& piles, int H) { int l = 1; int r = *max_element(begin(piles), end(piles)) + 1; while (l < r) { int m = (r - l) / 2 + l; int h = 0; for (int p : piles) h += (p + m - 1) / m; if (h <= H) r = m; else l = m + 1; } return l; } }; |

