[LeetCode] Koko Eating Bananas

875. Koko Eating Bananas

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
inline long search(vector<int>& p, long m) {
return accumulate(begin(p), end(p), 0l, [&](long sum, int b) {
return sum + ceil(1.0 * b / m);
});
}
public:
int minEatingSpeed(vector<int>& piles, int h) {
long l = 1, r = INT_MAX;
while(l <= r) {
long m = (l + r) / 2;
long s = search(piles, m);
if(s > h) l = m + 1;
else r = m - 1;
}
return l;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/27/PS/LeetCode/koko-eating-bananas/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.