Skip to content

875. Koko Eating Bananas 👍

  • Time: $O(n\log(\max(\texttt{piles})))$
  • Space: $O(1)$
 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
class Solution {
 public:
  int minEatingSpeed(vector<int>& piles, int h) {
    int l = 1;
    int r = ranges::max(piles);

    while (l < r) {
      const int m = (l + r) / 2;
      if (eatHours(piles, m) <= h)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

 private:
  // Returns the hours to eat all the piles with speed m.
  int eatHours(const vector<int>& piles, int m) {
    return accumulate(piles.begin(), piles.end(), 0,
                      [&](int subtotal, int pile) {
      return subtotal + (pile - 1) / m + 1;  // ceil(pile / m)
    });
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int minEatingSpeed(int[] piles, int h) {
    int l = 1;
    int r = Arrays.stream(piles).max().getAsInt();

    while (l < r) {
      final int m = (l + r) / 2;
      if (eatHours(piles, m) <= h)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

  // Returns the hours to eat all the piles with speed m.
  private int eatHours(int[] piles, int m) {
    return Arrays.stream(piles).reduce(
        0, (subtotal, pile) -> subtotal + (pile - 1) / m + 1); // ceil(pile / m)
  }
}
1
2
3
4
5
6
7
class Solution:
  def minEatingSpeed(self, piles: list[int], h: int) -> int:
    def eatHours(m: int) -> bool:
      """Returns True if Koko can eat all piles with speed m."""
      return sum((pile - 1) // m + 1 for pile in piles) <= h
    return bisect.bisect_left(range(1, max(piles)), True,
                              key=lambda m: eatHours(m)) + 1