Koko Eating Bananas in Java: Explanation & Practice
Minimum eating speed to finish in h hours
Problem summary
Koko can decide her eating speed k (bananas per hour). Each hour she eats k bananas from one pile. Find minimum k to finish all piles in h hours.
Starter code
public class Main {
public static void main(String[] args) {
int[] piles = {3, 6, 7, 11};
int h = 8;
// Binary search on eating speed k
// Min k = 1, Max k = max pile size
// For each k, calculate hours needed
// Print: Min speed: 4
}
}Expected output and test cases
- [3,6,7,11], h=8
Min speed: 4
- [30,11,23,4,20], h=5
Min speed: 30
- [30,11,23,4,20], h=6
Min speed: 23
Hints
- Binary search on the answer (eating speed)
- For speed k, hours needed = sum of ceil(pile[i]/k) for all piles
- If hours needed <= h, try smaller speed (right = mid)
- If hours needed > h, need faster speed (left = mid + 1)
Related Data Structures & Algorithms exercises
- Practice Search in Rotated Sorted Array in Java
- Practice Find Minimum in Rotated Sorted Array in Java
- Practice Capacity To Ship Packages in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler