875. Koko Eating Bananas

;  |     Back to Homepage   |     Back to Code List


class Solution {
    public int minEatingSpeed(int[] piles, int h) {
        int lo = 1, hi = 0;
        for (int pile : piles) {
            hi = Math.max(hi, pile);
        }
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            int hours = getHours(piles, mid);
            if (hours <= h) {
                hi = mid;
            } else {
                lo = mid + 1;
            }
        }
        return lo;
    }

    private int getHours(int[] piles, int speed) {
        int totalHours = 0;
        for (int pile : piles) {
            // 1~4: 1 hour
            // 3/4
            // (4 + 4)/4=2
            totalHours += (pile + speed - 1) / speed;
        }
        return totalHours;
    }
}