BackendML

Koko Eating Bananas

Medium2 min read
The Koko Eating Bananas problem requires finding the minimum eating speed that allows Koko to finish all bananas within a given number of hours.

Problem

Given an integer array piles, where each value represents the number of bananas in a pile, and an integer h, representing the total number of hours available, find the minimum integer eating speed k such that Koko can eat all the bananas within h hours.

Koko can eat at most k bananas per hour from a single pile. If a pile contains fewer than k bananas, she finishes that pile within one hour.

Example(s)

Example 1

Input
piles = [3,6,7,11]
h = 8
Output
4

Example 2

Input
piles = [30,11,23,4,20]
h = 5
Output
30

Solution

This problem can be solved using Binary Search on the Answer. Instead of searching for a value in the array, we search for the minimum possible eating speed.

The minimum possible speed is 1, while the maximum possible speed is the largest pile. For a candidate speed mid, we calculate the total hours required.

If Koko can finish all bananas within h hours, the speed is possible, so we try a smaller speed. Otherwise, we need a larger speed.

The key observation is that if a particular speed is sufficient, every larger speed is also sufficient. If a speed is not sufficient, every smaller speed is also insufficient. This monotonic property allows us to use Binary Search.
class Solution {
    public int minEatingSpeed(int[] piles, int h) {
        int left = 1;
        int right = 0;

        for (int pile : piles) {
            right = Math.max(pile, right);
        }

        int speed = right;
        while (left <= right) {
            int mid = left + (right - left) / 2;

            long hours = 0;
            for (int pile : piles) {
                hours += pile / mid;
                if (pile % mid != 0) {
                    hours++;
                }
            }

            if (hours > h) {
                left = mid + 1;
            } else {
                speed = Math.min(speed, mid);
                right = mid - 1;
            }
        }
        return speed;
    }
}

Complexity

Let n be the number of piles and M be the maximum pile size. Binary Search performs O(log M) iterations, and each iteration checks all n piles. Therefore, the time complexity is O(n log M).

The algorithm uses only a few variables, so the extra space complexity is O(1).

Comments

No comments yet. Ask a question or share what helped.