LeetCode Solutions

875. Koko Eating Bananas

Time: $O(n\log(\max(\texttt{piles})))$

Space: $O(1)$

			

class Solution {
 public:
  int minEatingSpeed(vector<int>& piles, int h) {
    int l = 1;
    int r = *max_element(begin(piles), end(piles));

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

    return l;
  }

 private:
  // Hours to eat all piles with speed m
  int eatHours(const vector<int>& piles, int m) {
    return accumulate(begin(piles), end(piles), 0, [&](int subtotal, int pile) {
      return subtotal + (pile - 1) / m + 1;  // Ceil(pile / m)
    });
  }
};
			

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;
  }

  // Hours to eat all piles with speed m
  private int eatHours(int[] piles, int m) {
    return Arrays.stream(piles).reduce(
        0, (subtotal, pile) -> subtotal + (pile - 1) / m + 1); // Math.ceil(pile / m)
  }
}
			

class Solution:
  def minEatingSpeed(self, piles: List[int], h: int) -> int:
    l = 1
    r = max(piles)

    # Hours to eat all piles with speed m
    def eatHours(m: int) -> int:
      return sum((pile - 1) // m + 1 for pile in piles)

    while l < r:
      m = (l + r) // 2
      if eatHours(m) <= h:
        r = m
      else:
        l = m + 1

    return l