Introduction
Koko Eating Bananas means:
- finding minimum eating speed
to finish banana piles
within given hours
Rule:
Koko can eat k bananas per hour from one pile.Goal:
- minimize eating speed
while finishing bananas
within h hours
Example:
Piles:
[3,6,7,11]
Hours:
8
Output:4
Explanation:
Eating speed 4 allows Koko to finish within 8 hours. This problem is one of the most important applications of:
Binary Search on Answer Constraints
1 <= piles.length <= 10^5 Approach : Binary Search on Answer
Explanations:
Explanation:
The idea is:
- search possible eating speed
instead of searching array index - validate each speed efficiently
Search Space:
Minimum speed = 1Maximum speed = max(piles)
Steps:
- Select middle speed.
- Calculate required hours.
- Check if valid.
- Reduce answer range.
- Continue binary search.
Hour Calculation:
hours += ceil(pile / speed) Conditions:
requiredHours <= h → valid speed requiredHours > h → increase speed This approach:
- optimizes answer searching
- avoids brute force checking
Dry Run
Piles:[3,6,7,11]
Middle speed:
6
Required hours:
6
Valid speed found.
Try smaller speed.
Middle speed:
4
Required hours:
8
Minimum valid speed:
4
Practice :