7 April 2024

Medium

875. Koko Eating Bananas

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

Description: Find the minimum integer speed at which Koko can eat all the bananas within the given time.

Solution:

Koko can eat bananas at a certain speed. We can use binary search to find the minimum speed at which Koko can eat all the bananas within the given time. We can start with the minimum possible speed and the maximum speed needed. Do loop to find the mid speed and check if Koko can finish eating all the bananas within the given time. If Koko can finish, we can try slower speeds to find the minimum speed. If Koko cannot finish, we need to try faster speeds. We can return the minimum speed at which Koko can eat all the bananas within the given time because the left pointer will be at the minimum speed.

/**
 * @param {number[]} piles
 * @param {number} h
 * @return {number}
 */
var minEatingSpeed = function (piles, h) {
  let left = 1 // Minimum possible speed.
  let right = Math.max(...piles) // Maximum speed needed.

  const canFinish = (k) => {
    let time = 0
    for (let pile of piles) {
      time += Math.ceil(pile / k) // Calculate hours needed with speed k.
    }
    return time <= h // Check if Koko can finish eating in h or fewer hours.
  }

  while (left < right) {
    let mid = Math.floor((left + right) / 2)
    if (canFinish(mid)) {
      right = mid // Koko can finish with this speed, try slower to find minimum.
    } else {
      left = mid + 1 // Too slow, need faster speed.
    }
  }

  return left // Left is the minimum speed Koko can eat all bananas within h hours.
}