Data Structures & AlgorithmsHardProduct Company SDE · binary search on answer

Problem: Koko eats bananas from piles [3, 6, 7, 11] and has h = 8 hours. She picks one pile per hour and eats up to k bananas from it. What is the minimum integer k that finishes in time? Run the binary search code.

Problem: Koko eats bananas from piles [3, 6, 7, 11] and has h = 8 hours. She picks one pile per hour and eats up to k bananas from it. What is the minimum integer k that finishes in time? Run the binary search code.
import math
piles = [3, 6, 7, 11]
h = 8
lo, hi = 1, max(piles)
while lo < hi:
    mid = (lo + hi) // 2
    hours = sum(math.ceil(p / mid) for p in piles)
    if hours <= h:
        hi = mid
    else:
        lo = mid + 1
print(lo)
What is printed?
  1. A. 3
  2. B. 4
  3. C. 5
  4. D. 6

Correct answer: B. 4

At k = 4 the hours are 1 + 2 + 2 + 3 = 8, while k = 3 needs 1 + 2 + 3 + 4 = 10 hours. Hours decrease monotonically in k, which is what makes binary search valid.

More Coding Interview Problems questions

Exams that ask this topic