Leetcode-875

Koko Eating Bananas

Time complexity: $O(n\log M)$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <vector>

class Solution {
public:
    int minEatingSpeed(std::vector<int>& piles, int h) {
        int n = piles.size();
        
        int left = 1, right = 0;
        for (int i : piles) {
            right = std::max(i, right);
        }
        h -= n;
        if (h == 0) {
            return right;
        }
        
        for (int mid = (left + right) / 2; right > left;) {
            if (check(piles, h, mid)) {
                right = mid;
            }
            else {
                left = mid + 1;
            }
            mid = (left + right) / 2;
        }
        
        return left;
    }
    
private:
    bool check(std::vector<int> piles, int h, int speed) {
        for (int i : piles) {
            h -= (i - 1) / speed;
            if (h < 0) {
                return false;
            }
        }
        return true;
    }
};

Leetcode-875