Leetcode 907 Solution

This article provides solution to leetcode question 907 (koko-eating-bananas)

https://leetcode.com/problems/koko-eating-bananas

Solution

class Solution {
public:
    int getEatingHours(vector<int>& piles, int K) {
        int hours = 0;
        for (int pile: piles)
            hours += (pile + K - 1) / K;
        return hours;
    }

    int minEatingSpeed(vector<int>& piles, int H) {
        int max_pile = 0;
        for (int pile: piles)
            max_pile = max(max_pile, pile);

        int l = 1;
        int r = max_pile;

        while (l < r)
        {
            int m = (l + r) / 2;

            if (getEatingHours(piles, m) <= H)
                r = m;
            else
                l = m + 1;
        }

        return l;
    }
};