Binary Search
Medium

Apple Harvest (Koko Variant)

Find the minimum eating speed to finish all piles within H hours.
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 allow 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
Step 1 / 1

Initializing...

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep