Browse curriculum

FAANGPrep Sprint

Apple Harvest (Koko Variant)

Find the minimum eating speed to finish all piles within H hours.

Medium
20 min
Solve on LeetCode

Problem Understanding

You have n piles of apples. The i-th pile has piles[i] apples.
You have H hours to eat all apples.

You can decide your eating speed k (apples per hour).

  • Each hour, you choose a pile and eat up to k apples from it.
  • If the pile has less than k apples, you eat them all and stop for that hour (you don't move to the next pile).

Return the minimum integer k such that you can eat all apples within H hours.

Example

  • Piles: [3, 6, 7, 11], H: 8
  • If k=1: Needs 3+6+7+11 = 27 hours (> 8). Too slow.
  • If k=4: Needs 1+2+2+3 = 8 hours (<= 8). Valid.
  • Can we do better? Minimum k is our goal.

Attempt 1: Brute Force (Linear Search on k)

The possible speeds range from k=1 (slowest) to k=max(piles) (fastest - one pile per hour).
We can check every k starting from 1.

  1. Try k=1. Calculate hours. If <= H, return 1.
  2. Try k=2. Calculate hours. If <= H, return 2.
  3. ...

Time Complexity

O(max(P) * n). If max pile is 10^9, this is TLE (Time Limit Exceeded).

The Intuition: Binary Search on Answer

The valid speeds form a monotonic range:

  • If speed k is valid (we finish in time), then any speed > k is also valid (we finish even faster).
  • If speed k is invalid (too slow), then any speed < k is also invalid.

This monotonicity allows us to use Binary Search on the search space of k (from 1 to max(piles)).

  • Range: [1, max(piles)]
  • Mid: Test if speed mid is feasible.
    • If feasible (hours <= H): This mid could be the minimum, but maybe there's a smaller one? Store mid as answer, and search left (high = mid - 1).
    • If not feasible (hours > H): Too slow! Need faster speed. Search right (low = mid + 1).

Interactive Visualization

FINISH WITHIN 8 HOURS

READY

3

6

7

11

Low

1

High

11

Speed k

—

Hours

—

Best k

11

 

Speeds from 1 to 11 are possible. Start with answer = 11: at the largest pile's size, every pile takes one hour

Next

Try the middle speed of [1, 11]: k = 6

Piles

Hours (h)

Step through the search on k and watch each speed’s total hours compared against H.