CodeArchon

mediumBinary SearchAmazonGoogle

Banana Pacing Rate

A koala eats at some fixed rate k bananas/hour from several piles. Find the slowest rate that finishes within h hours.

Given `piles` (sizes) and `h` (hours), return the minimum integer rate k such that total eating time ≤ h.

Choose approach

3
0
6
1
7
2
11
3
Maptrial
empty
1/6
Narrationstep 1 of 6

Search eating rate k ∈ [1, max(piles)=11]. A faster k is always feasible — this is monotonic.

1import math
2
3def banana_pacing_rate(piles: list[int], h: int) -> int:
4 def feasible(k: int) -> bool:
5 return sum(math.ceil(p / k) for p in piles) <= h
6 lo, hi = 1, max(piles)
7 while lo < hi:
8 mid = (lo + hi) // 2
9 if feasible(mid):
10 hi = mid
11 else:
12 lo = mid + 1
13 return lo
Variables
lo=1
hi=11
h=8

How to think about it

  1. Faster = fewer hours — monotonic structure on the rate axis.
  2. Lo = 1 (can't eat 0). Hi = max pile (never need faster).
  3. Each probe is O(n) to sum ceil(pile/k).
  4. O(log(max)) probes → O(n log max) overall.

Edge cases to catch in interview

  • h = n → must finish each pile in one hour → rate = max pile.
  • Very big h → rate = 1.
  • One huge pile → rate = ceil(pile / h) effectively.

Examples

Example 14
{"piles":[3,6,7,11],"h":8,"values":[3,6,7,11]}
Example 230
{"piles":[30,11,23,4,20],"h":5,"values":[30,11,23,4,20]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed