Algo-Sim › Binary Search

Koko Eating Bananas

Medium · Binary Search · step through it in Java, Python and C++ on your own input

Find the slowest eating speed that finishes every pile within h hours. Binary search on the answer.

Problem

There are piles[i] bananas in pile i, and the guards return in h hours. Each hour Koko picks one pile and eats k bananas from it; if the pile has fewer than k, she eats all of it and waits out the hour. Return the smallest integer k that lets her eat every banana within h hours.

Constraints

Edge cases to test

Follow-up questions

How do you count hours without floating point?
(pile + speed − 1) / speed is the ceiling of the division in integers.
What makes a problem "binary search on the answer"?
A yes/no check that is monotonic in the answer (faster always finishes if slower does). Search the smallest yes: O(n log max).

Solution

Java

public int minEatingSpeed(int[] piles, int h) {
    int lo = 1, hi = Arrays.stream(piles).max().getAsInt(), ans = hi;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (hoursAt(piles, mid) <= h) {
            ans = mid; hi = mid - 1;
        } else {
            lo = mid + 1;
        }
    }
    return ans;
}

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

Python

def min_eating_speed(piles, h):
    lo, hi = 1, max(piles)
    ans = hi
    while lo <= hi:
        mid = lo + (hi - lo) // 2
        if hours_at(piles, mid) <= h:
            ans, hi = mid, mid - 1
        else:
            lo = mid + 1
    return ans


def hours_at(piles, speed):
    hours = 0
    for p in piles:
        hours += (p + speed - 1) // speed
    return hours

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int minEatingSpeed(vector<int> &piles, int h) {
        int lo = 1, hi = *max_element(piles.begin(), piles.end()), ans = hi;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (hoursAt(piles, mid) <= h) {
                ans = mid;
                hi = mid - 1;
            } else {
                lo = mid + 1;
            }
        }
        return ans;
    }

    long long hoursAt(vector<int> &piles, int speed) {
        long long hours = 0;
        for (int p : piles)
            hours += (p + speed - 1) / speed;
        return hours;
    }
};

More Binary Search problems