0875. Koko Eating Bananas
Medium | Binary Search | 372 ms (97.73%), 15.5 MB (87.10%)
Input: piles = [3,6,7,11], h = 8
Output: 4
Input: piles = [30,11,23,4,20], h = 5
Output: 30
Input: piles = [30,11,23,4,20], h = 6
Output: 23class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
# ==================================================
# Binary Search =
# ==================================================
# time : O(nlog(m)), m is the search space
# space : O(1)
l, r = 1, max(piles)
while l < r:
speed = (l + r) // 2
if sum(ceil(pile / speed) for pile in piles) <= h: r = speed
else: l = speed + 1
return lclass Solution {
/**
* @time : O(nlog(m)), m is the search space
* @space : O(1)
*/
public int minEatingSpeed(int[] piles, int h) {
int l = 1, r = 1000000000;
while (l < r) {
int m = (l + r) / 2, total = 0;
for (int p : piles) total += (p - 1) / m + 1;
if (total <= h) r = m;
else l = m + 1;
}
return l;
}
}Last updated