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

  1. Binary search on the answer (eating speed)
  2. For speed k, hours needed = sum of ceil(pile[i]/k) for all piles
  3. If hours needed <= h, try smaller speed (right = mid)
  4. If hours needed > h, need faster speed (left = mid + 1)

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler