Advertisement
DeepRest

Koko Eating Bananas

Jan 19th, 2022 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.15 KB | None | 0 0
  1. '''
  2. Binary Search on answer
  3. Since time taken to eat all bananas is monotonically decreasing with eating speed k. (Time inversely proportional to speed)
  4. If for given speed k, time taken to eat all bananas is less than equal to h, then consider lower half of k...koku has to slow down(as upper half of speed will surely have lesser or equal time to eat).
  5. Similiarly, if for given speed k if koku is not able to finish all bananas then he has to speed up(lower half of speed will result in more time...thus consider upper half)
  6. Bounds of search space:
  7. Lowest possible speed: 1 banana per hour, will finish all of them in sum(piles) hour
  8. Upper bound: At speed of max(piles) banana per hour koku will finish one pile per hour(total time=len(piles)).
  9. This is upper bound as koku can finish at most 1 pile in one hour.
  10. '''
  11. class Solution:
  12.     def minEatingSpeed(self, piles: List[int], h: int) -> int:
  13.         lo, hi = 1, max(piles)
  14.         while lo<hi:
  15.             mid = (lo+hi)//2
  16.             tim = sum(ceil(i/mid) for i in piles)
  17.             if h >= tim:
  18.                 hi = mid
  19.             else:
  20.                 lo = mid+1
  21.         return lo
  22.            
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement