Menu
CoddyTech

Koko Eating Bananas

MediumBinary searchpython iconjava iconcpp iconc iconjs icon+10

Koko has n piles of bananas, where piles[i] is the number of bananas in pile i, and h hours before the guards come back. She picks one eating speed k, a whole number of bananas per hour, and keeps it. Each hour she eats k bananas from one pile; if that pile has fewer than k left, she finishes it and rests until the hour is over. Return the smallest speed k that lets her finish every pile within h hours.

Function

minEatingSpeed(piles: integer-array, h: integer) → integer
pilesinteger-array
the number of bananas in each pile
hinteger
the number of hours Koko has
Returnsinteger
the smallest whole eating speed, in bananas per hour, that finishes every pile within h hours

Constraints

  • 1 ≤ piles.length ≤ 5000
  • 1 ≤ piles[i] ≤ 109
  • piles.length ≤ h ≤ 109, so an answer always exists.

Examples

Input
piles = [4, 10, 7, 3]h = 6
Output
5
Explanation
At speed 5 the piles 4, 10, 7 and 3 take 1, 2, 2 and 1 hours: 6 in total, which fits. At speed 4 they take 1, 3, 2 and 1 hours, which is 7, one hour too many.

lock icon+22 hidden tests on Submit

challenge icon

Follow-up

A twin problem: Koko has d days and eats whole piles in the given order, as many piles a day as fit in a daily limit of k bananas. What is the smallest k, and which two parts of your binary search change?

Reset code
def minEatingSpeed(piles, h):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

piles = [4, 10, 7, 3]
h = 6

Expected

5