ZhongKuo0228 / study

0 stars 0 forks source link

875. Koko Eating Bananas #112

Open fockspaces opened 11 months ago

fockspaces commented 11 months ago

use Binary search to find the minimun speed to eat

  1. set boundary
  2. l = 1 (we should at least eat one per hour), r = max(piles) (if we keep the speed of max amount in piles, we can finish in len(piles) hour)
  3. keep updating, we want to search the most left possible one, the base case is total_hour > h, it means we eat too slow, should be more aggresive to eat
class Solution:
    def minEatingSpeed(self, piles: List[int], h: int) -> int:
        l, r = 1, max(piles)
        while l < r:
            mid = (l + r) // 2
            total_hour = 0
            for pile in piles:
                spend_hour = math.ceil(pile / mid)
                total_hour += spend_hour
            if total_hour > h:
                l = mid + 1
            else:
                r = mid
        return l