875.Koko Eating Bananas
===
###### tags: `Medium`,`Array`,`Binary Search`
[875. Koko Eating Bananas](https://leetcode.com/problems/koko-eating-bananas/)
### 題目描述
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 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 3:**
```
Input: piles = [30,11,23,4,20], h = 6
Output: 23
```
**Constraints**:
* 1 <= `piles.length` <= 10^4^
* `piles.length` <= `h` <= 10^9^
* 1 <= `piles[i]` <= 10^9^
### 解答
#### Python
```python=
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
l, r = 1, max(piles)
def feasible(speed):
time = 0
for pile in piles:
time += math.ceil(pile / speed)
return time <= h
while l < r:
m = l + (r - l) // 2
if feasible(m):
r = m
else:
l = m + 1
return l
```
發現可以縮一下
```python=
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
l, r = 1, max(piles)
def feasible(speed):
return sum(math.ceil(pile / speed) for pile in piles) <= h
while l < r:
m = l + (r - l) // 2
if feasible(m):
r = m
else:
l = m + 1
return l
```
> [name=Ron Chen][time=Wed, Mar 8, 2023]
#### Javascript
```javascript=
function minEatingSpeed(piles, h) {
let min = 1;
let max = Math.max(...piles) * h;
while (max > min) {
const mid = Math.floor((max + min) / 2);
let time = 0;
for (const pile of piles) {
time += Math.ceil(pile / mid);
}
if (time > h) {
min = mid + 1;
} else {
max = mid;
}
}
return min;
}
```
> 寫這麼多天Binary search了今天終於一次過。
> [name=Marsgoat][time=Wed, Mar 8, 2023]
### Reference
[回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)