Koko loves to eat bananas. There are n
piles of bananas, the ith
pile has piles[i]
bananas. The guards have gone and will come back in h
hours.
Koko can decide her bananas-per-hour eating speed of k
. Each hour, she chooses some pile of bananas and eats k
bananas from that pile. If the pile has less than k
bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer k
such that she can eat all the bananas within h
hours.
Solution
If we have k = max(piles)
, we will always be able to finish within h
hours, we will always be able to finish. So, we essentially just want to try all the numbers between 1, ... , max(piles)
until we find the minimum which allows us to eat all the bananas within h
hours. This can be done using a binary search.
Time: , Space:
Notes:
- We need to assume
len(p) < h
for this to work. math.ceil
is used to find ceiling – we always round up, e.g. 8 bananas with would take 3 hours.- We can take
float(p)
to ensure floating point results, although this is technically unnecessary in Python 3.