July 14, 2022

875. Koko Eating Bananas

875. Koko Eating Bananas

Sol 0. Brute Force (Time Limit Exceeded)

n is len(piles), m is max number of bananas. Time = O(nm)

class Solution {
    public int minEatingSpeed(int[] piles, int h) {

        int speed = 1;
        while (true) {
            int totalHours = 0;
            for (int i = 0; i < piles.length; i++) {
                int hours = piles[i] / speed;
                if (piles[i] % speed != 0) {
                    hours += 1;
                }
                totalHours += hours;
                if (totalHours > h) {
                    break;
                }
            }
            if (totalHours <= h) {
                return speed;
            } else {
                speed += 1;
            }
        }
    }
}

n is len(piles), m is max number of bananas. Time = O(nlogm)

class Solution {
    public int minEatingSpeed(int[] piles, int h) {
        int left = 1;
        int right = 1;
        for (int pile : piles) {
            right = Math.max(right, pile);
        }
        
        while (left < right) {
            int mid = (left + right) / 2;
            int totalHours = 0;
            for (int i = 0; i < piles.length; i++) {
                int hours = piles[i] / mid;
                if (piles[i] % mid != 0) {
                    hours += 1;
                }
                totalHours += hours;
                if (totalHours > h) {
                    break;
                }
            }
            
            if (totalHours <= h) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return right;
    }
}
comments powered by Disqus