# Problem Statement 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_. ## Constraints - `1 <= piles.length <= ` $10^4$ - `piles.length <= h <= `$10^9$ - `1 <= piles[i] <= ` $10^9$ # Solution We can solve this problem by doing a [[Binary Search On Answer|binary search on the answer]]. Since the hours required is monotonic (if we can finish in $n$ hours, we can finish in $n+1$ hours and if we can't finish in $n$ hours we can't finish in $n-1$ hours), we can use binary search on the number of hours to get the minimum efficiently. Our predicate function will be `canEatAllPiles` which takes in `eatingSpeed` and returns whether or not Koko can eat all the piles with an eating speed of `eatingSpeed` within `h` hours. ```python def canEatAllPiles(eatingSpeed): totalHoursTaken = 0 for pile in piles: pileHours = ceil(pile / eatingSpeed) totalHoursTaken += pileHours return totalHoursTaken <= h ``` Then we use this predicate function as our key in a binary search from `1` to `max(piles)`. ```python def canEatAllBananas(eatingSpeed): totalHoursTaken = 0 for pile in piles: pileHours = ceil(pile / eatingSpeed) totalHoursTaken += pileHours return totalHoursTaken <= h return bisect_left(range(max(piles)),True,lo=1,key=canEatAllBananas) ``` Time Complexity: O$(n\log m)$ | Space Complexity: $O(1)$