---
# System prepended metadata

title: Leetcode 875. Koko Eating Bananas
tags: [Leetcode]

---

[link](https://leetcode.com/problems/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.

#### 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 2:

Input: piles = [30,11,23,4,20], h = 6
Output: 23

#### Constraints:

- 1 <= piles.length <= 104
- piles.length <= h <= 109
- 1 <= piles[i] <= 109
---

The method starts by initializing two variables, l and r, to 1 and the maximum value in piles, respectively. It also initializes a variable res to r.

The method then enters a while loop that continues as long as l is less than or equal to r. Inside the loop, it calculates the middle value mid as the average of l and r.

Next, it initializes a variable hrs to 0, which will store the total hours required to eat all the bananas at the current eating speed (mid). It iterates over each pile in piles and calculates the number of hours required to eat that pile at the current speed, using the math.ceil() function to round up to the nearest integer.

After calculating the total hours required (hrs), the method checks if it is less than or equal to the available hours (h). If it is, it updates res to the minimum of the current speed (mid) and the previous minimum (res). It then updates r to mid - 1 to search for lower eating speeds.

If the total hours required is greater than the available hours, the method updates l to mid + 1 to search for higher eating speeds.

The loop continues until l becomes greater than r, at which point the method returns the minimum eating speed stored in res.

#### Solution 1
```python=
class Solution:
    def minEatingSpeed(self, piles: List[int], h: int) -> int:
        l, r = 1, max(piles)
        res = r
        while l <= r:
            mid = l + (r - l) // 2
            hrs = 0
            for p in piles:
                hrs += math.ceil(p / mid)
            
            if hrs <= h:
                res = min(mid, res)
                r = mid - 1
        
            else:
                l = mid + 1

        return res
        
```
O(T): O(T*log(S))
O(S): O(1)