English
875. Koko Eating Bananas
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.
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 <= 104
piles.length <= h <= 109
1 <= piles[i] <= 109
Solution:
rs
impl Solution {
pub fn min_eating_speed(piles: Vec<i32>, h: i32) -> i32 {
let mut min_spd = 1;
let mut max_spd = piles.iter().max().unwrap().clone();
while min_spd < max_spd {
let speed = (min_spd + max_spd) / 2;
let hours = piles
.iter()
.fold(0, |subtotal, &pile| subtotal + ((pile + speed - 1) / speed));
if hours > h {
min_spd = speed + 1;
} else {
max_spd = speed;
}
}
min_spd
}
}
py
import math
class Solution:
def minEatingSpeed(self, p: list[int], h: int) -> int:
left, right = 1, max(p)
while left <= right:
m = (left+right)//2
# t = sum((i+m-1)//m for i in p)
# t = sum(-(-i//m) for i in p)
t = sum(math.ceil(i/m) for i in p)
if t > h:
left = m+1
else:
right = m-1
return left
...