← Binary Search

Koko Eating Bananas

Medium
Python
def min_eating_speed(piles,h):
    import math
    l,r=1,max(piles)
    while l<r:
        mid=(l+r)//2
        hours=sum(math.ceil(p/mid) for p in piles)
        if hours<=h: r=mid
        else: l=mid+1
    return l
Java
public int minEatingSpeed(int[] piles,int h){
    int l=1,r=0;
    for(int p:piles) r=Math.max(r,p);
    while(l<r){
        int mid=(l+r)/2;
        int hours=0;
        for(int p:piles) hours+=(p+mid-1)/mid;
        if(hours<=h) r=mid;
        else l=mid+1;
    } return l;
}

Key Insight

Python math.ceil() vs Java ceiling trick (p+mid-1)/mid.

Python → Java Differences

  • math.ceil(p/mid) vs (p+mid-1)/mid
  • sum() generator vs Java loop
  • Binary search on answer identical
Python
def min_eating_speed(piles,h):
    import math
    l,r=1,max(piles)
    while l<r:
        mid=(l+r)//2
        hours=sum(math.ceil(p/mid) for p in piles)
        if hours<=h: r=mid
        else: l=mid+1
    return l
Java
public int minEatingSpeed(int[] piles,int h){
    int l=1,r=0;
    for(int p:piles) r=Math.max(r,p);
    while(l<r){
        int mid=(l+r)/2;
        int hours=0;
        for(int p:piles) hours+=(p+mid-1)/mid;
        if(hours<=h) r=mid;
        else l=mid+1;
    } return l;
}

Algorithm Steps

1. Binary search on speed
2. Check feasibility