|
| 1 | +# Time: O(nlogr) |
| 2 | +# Space: O(1) |
| 3 | + |
| 4 | +# Koko loves to eat bananas. |
| 5 | +# There are N piles of bananas, the i-th pile has piles[i] bananas. |
| 6 | +# The guards have gone and will come back in H hours. |
| 7 | +# |
| 8 | +# Koko can decide her bananas-per-hour eating speed of K. |
| 9 | +# Each hour, she chooses some pile of bananas, and eats K bananas from that pile. |
| 10 | +# If the pile has less than K bananas, she eats all of them instead, |
| 11 | +# and won't eat any more bananas during this hour. |
| 12 | +# |
| 13 | +# Koko likes to eat slowly, but still wants to finish eating |
| 14 | +# all the bananas before the guards come back. |
| 15 | +# |
| 16 | +# Return the minimum integer K such that she can eat all the bananas within H hours. |
| 17 | +# |
| 18 | +# Example 1: |
| 19 | +# |
| 20 | +# Input: piles = [3,6,7,11], H = 8 |
| 21 | +# Output: 4 |
| 22 | +# Example 2: |
| 23 | +# |
| 24 | +# Input: piles = [30,11,23,4,20], H = 5 |
| 25 | +# Output: 30 |
| 26 | +# Example 3: |
| 27 | +# |
| 28 | +# Input: piles = [30,11,23,4,20], H = 6 |
| 29 | +# Output: 23 |
| 30 | +# |
| 31 | +# Note: |
| 32 | +# - 1 <= piles.length <= 10^4 |
| 33 | +# - piles.length <= H <= 10^9 |
| 34 | +# - 1 <= piles[i] <= 10^9 |
| 35 | + |
| 36 | +class Solution(object): |
| 37 | + def minEatingSpeed(self, piles, H): |
| 38 | + """ |
| 39 | + :type piles: List[int] |
| 40 | + :type H: int |
| 41 | + :rtype: int |
| 42 | + """ |
| 43 | + def possible(piles, H, K): |
| 44 | + return sum((pile-1)//K+1 for pile in piles) <= H |
| 45 | + |
| 46 | + left, right = 1, max(piles) |
| 47 | + while left <= right: |
| 48 | + mid = left + (right-left)//2 |
| 49 | + if possible(piles, H, mid): |
| 50 | + right = mid-1 |
| 51 | + else: |
| 52 | + left = mid+1 |
| 53 | + return left |
0 commit comments