Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Koko eats from one pile per hour at speed k bananas/hour (if a pile has fewer, she finishes it and waits). Find the minimum k to finish within h hours.

Problem: Koko eats from one pile per hour at speed k bananas/hour (if a pile has fewer, she finishes it and waits). Find the minimum k to finish within h hours.
def koko(piles, h):
    lo, hi = 1, max(piles)
    while lo < hi:
        k = (lo + hi) // 2
        if sum((p + k - 1) // k for p in piles) <= h: hi = k
        else: lo = k + 1
    return lo
print(koko([9, 25, 14, 7], 8))
What is printed?
  1. A. 6
  2. B. 7
  3. C. 9
  4. D. 5

Correct answer: C. 9

Speed 9: 1 + 3 + 2 + 1 = 7 hours ≤ 8, while speed 8 needs 2 + 4 + 2 + 1 = 9 hours, so 9. Floor division p // k forgets the partial hour and gives 6, ceil(55 / 8) = 7 assumes piles can be shared across hours, and giving all four spare hours to the biggest pile (ceil(25 / 5)) gives 5 but ignores the pile of 14.

More Coding Interview Problems questions

Exams that ask this topic