Koko Eating Bananas

Find the slowest eating speed that still clears every pile of bananas in the hours available.

Koko has some piles of bananas, given as an array piles, where piles[i] is the number of bananas in pile i. She has h hours before the guards come back. Each hour she picks one pile and eats k bananas from it. If that pile has fewer than k bananas left, she eats them all and does nothing else for the rest of the hour. Return the smallest whole number k that lets her finish every pile within h hours. A pile holds at most 1,000,000,000 bananas, and the number of hours is never smaller than the number of piles.

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
Example 3
Input: piles = [30, 11, 23, 4, 20], h = 6
Output: 23
Solution

The Idea

Think of a stack of work with a deadline: the faster you go, the sooner you finish, but going faster than needed is wasted effort. Koko wants the most relaxed pace, the speed k in bananas per hour, that still beats the deadline of h hours.

Take Example 1: piles of 3, 6, 7 and 11 bananas, and 8 hours. Try speed 4. The pile of 3 takes one hour. The pile of 6 takes two: 4 bananas, then the last 2. The pile of 7 also takes two, and the pile of 11 takes three. That is 1 + 2 + 2 + 3 = 8 hours, which just fits.

Notice that a pile of 6 at speed 4 costs two full hours, not one and a half. Koko never moves to another pile in the middle of an hour, so the hours for one pile are its size divided by the speed, rounded up.

So checking one speed is easy. But which speed should we check? Look at the picture below. It tries every speed from 1 to 11 on Example 1.

Speeds 1 to 11 for the piles 3, 6, 7, 11 with the hours each needs: 27, 15, 10, 8, 8, 6, 5, 5, 5, 5, 4. Speeds 1 to 3 are too slow for 8 hours, 4 to 11 are enough, and 4 is the first yes.

The row labelled hours never goes up as the speed goes up, because eating faster never makes a pile take longer. So the row labelled fits in 8? reads no, no, no, and then yes all the way to the end. It switches from no to yes exactly once, and the answer is the speed where it switches: the box marked first yes: 4.

A row that switches once can be searched without visiting every box. Check the speed in the middle. If it fits, the first yes is there or to its left, so the right half can be dropped. If it does not fit, the first yes is to its right, so the left half can be dropped. Each check halves the speeds still in play. Searching by halving like this is called binary search, and here it runs over possible answers rather than over the array itself.

Solution Approach

Four decisions turn the row of yes and no answers into code: which speeds to search, how to count the hours for one speed, how to narrow the range, and how big the hour count can get.

The range of speeds

Which speeds can be the answer? Speed 0 eats nothing, so the smallest candidate is 1. At the top, a speed equal to the largest pile finishes every pile in one hour, so it needs as many hours as there are piles. The problem promises h is at least that, so the largest pile always works and no faster speed is needed.

The simple way would be to try speeds 1, 2, 3 and so on until one fits. With piles of up to a billion bananas, that can mean a billion checks, each reading every pile. Binary search over the same range needs about 30 checks, because halving a billion 30 times brings it down to about one.

Counting the hours for one speed

How do we round up with integers? In Java, 7 / 4 is 1, because integer division drops the remainder. Adding speed - 1 before dividing fixes that: (7 + 3) / 4 is 2. If there is any remainder, the added speed - 1 carries the total to or past the next multiple of the speed, so the result goes up by one. A pile that divides evenly, like (8 + 3) / 4, still gives exactly 2.

Narrowing the range

How do the two ends of the range move? Keep lo as the slowest speed still possible and hi as the fastest. Check the speed in the middle, mid. If it fits, it might be the answer itself, so hi moves to mid, not past it. If it does not fit, it cannot be the answer, so lo moves to mid + 1. When lo and hi meet, they sit on the first speed that fits.

On Example 1 the range starts at 1 to 11. Speed 6 needs 6 hours and fits, so the range becomes 1 to 6. Speed 3 needs 10 hours and is too slow, so it becomes 4 to 6. Speed 5 fits, giving 4 to 5. Speed 4 fits, giving 4 to 4, and the search stops on 4.

Adding up the hours without overflow

Can the hour count get too big? A Java int stops at 2,147,483,647, about 2.1 billion, and three piles of a billion bananas at speed 1 need three billion hours. An hour total pushed past that limit wraps around to a large negative number, which is called overflow, and a negative total would wrongly look like it fits within h. Adding the hours into a long, which holds far bigger values, avoids it.

Java Solution

The method minEatingSpeed works in these steps:

  1. First, set lo to 1, the slowest speed, and set hi to the largest pile, found with one loop over piles.
  2. While lo is smaller than hi, take the middle speed mid, written as lo + (hi - lo) / 2.
  3. Ask the helper method hoursNeeded how many hours mid takes. It loops over the piles and adds the rounded-up hours for each one into hours, a long.
  4. If those hours fit within h, move hi to mid. Otherwise, move lo to mid + 1.
  5. When the loop ends, lo and hi are equal, and lo is the answer.

The main method runs the three examples, then a budget of one hour per pile, a single pile, a very generous budget, and three piles of a billion bananas.

Java
public class KokoEatingBananas {

    public static int minEatingSpeed(int[] piles, int h) {
        int lo = 1;                           // slowest possible speed
        int hi = 0;
        for (int p : piles) {
            hi = Math.max(hi, p);             // at the largest pile size, every pile takes 1 hour
        }
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (hoursNeeded(piles, mid) <= h) {
                hi = mid;                     // mid is fast enough; maybe slower also works
            } else {
                lo = mid + 1;                 // too slow
            }
        }
        return lo;
    }

    private static long hoursNeeded(int[] piles, int speed) {
        long hours = 0;
        for (int p : piles) {
            hours += (p + speed - 1) / speed; // ceil(p / speed) using integers
        }
        return hours;
    }

    public static void main(String[] args) {
        System.out.println(minEatingSpeed(new int[] {3, 6, 7, 11}, 8));
        System.out.println(minEatingSpeed(new int[] {30, 11, 23, 4, 20}, 5));
        System.out.println(minEatingSpeed(new int[] {30, 11, 23, 4, 20}, 6));
        System.out.println(minEatingSpeed(new int[] {3, 6, 7, 11}, 4));
        System.out.println(minEatingSpeed(new int[] {7}, 3));
        System.out.println(minEatingSpeed(new int[] {3, 6, 7, 11}, 100));
        int big = 1000000000;
        System.out.println(minEatingSpeed(new int[] {big, big, big}, 2000000000));
    }
}

Running it prints:

Output
4
30
23
11
3
1
2

The opening 4, 30 and 23 match the three examples. With 5 hours for 5 piles, Example 2 has one hour per pile, so the speed must be the largest pile, 30. Example 3 has one spare hour. At speed 23, the pile of 30 uses it and every other pile takes one hour, 6 in total. At speed 22, the pile of 23 needs two hours as well, which makes 7.

The 11 shows the same tight budget on Example 1: 4 hours for 4 piles. The 3 comes from a single pile of 7 with 3 hours, where speed 3 takes 3, 3 and then 1 banana. The 1 is the other end: with 100 hours, the slowest speed already fits.

The last line, 2, is the overflow check. Speed 1 would need 3,000,000,000 hours, more than the 2,000,000,000 allowed. Added up in an int, those hours overflow to -1,294,967,296, which looks like it fits. A version with an int total returns 1 for this input; the long total correctly rejects speed 1.

Rounding matters just as much. Counting a pile's hours with plain p / speed makes leftover bananas free, and that version returns 3 for Example 1. At speed 3, Koko really needs 10 hours, as the picture shows.

Complexity

The work is one hour count over all the piles for every speed the binary search tries.

  • Time: O(n log M), where n is the number of piles and M is the largest pile. Each check halves the speeds from 1 to M, so there are about log M checks, and each one reads all n piles in hoursNeeded.
  • Space: O(1). The search keeps only lo, hi and mid, and hoursNeeded adds into a single long.

The same search for the smallest value that is good enough solves Capacity to Ship Packages, where the value is a ship's capacity instead of a speed.