Koko Eating Bananas

Program for Koko Eating Bananas Problem

You are given an array piles, where each element piles[i] represents the number of bananas in the i-th pile. You also have h hours to eat all the bananas. You can choose an eating rate of k bananas per hour. In each hour, you can eat up to k bananas from one pile.

If a pile has fewer than k bananas, you finish that pile but cannot switch to another pile during the same hour.

Your task is to find the minimum value of k that allows you to eat all the bananas within h hours.

Koko Eating Bananas Problem

Explanation: With an eating rate of 2, you can eat the bananas in 6 hours. With an eating rate of 1, you would need 10 hours to eat all the bananas (which exceeds h=9), thus the minimum eating rate is 2.

Constraints:

  • 1 <= piles.length <= 1,000
  • piles.length <= h <= 1,000,000
  • 1 <= piles[i] <= 1,000,000,000

Program for Koko Eating Bananas Solution

Recommendation for Time and Space Complexity –You should aim for a solution with O(nlogm) time and O(1) space, where n is the size of the input array, and m is the maximum value in the array.

Hints for solving problems

Hint 1 :

Given h is always greater than or equal to the length of piles, can you determine the upper bound for the answer? How much time does it take Koko to eat a pile with x bananas?

Hint 2 :

It takes ceil(x / k) time to finish the x pile when Koko eats at a rate of k bananas per hour. Our task is to determine the minimum possible value of k. However, we must also ensure that at this rate, k, Koko can finish eating all the piles within the given h hours. Can you now think of the upper bound for k?

There are mainly 2 approach to solve this problem-

  1. Brute Force Method
  2. Binary Search Method

1. Brute Force Method

Iterate through each possible eating speed from 1 to the maximum pile size and check if Koko can finish all the bananas within the given hours.

  • Time complexity: O(m*n)
  • Space complexity: O(1)

where n is the length of the input array piles and m is the maximum number of bananas in a pile.

Code

2. Binary Search Method

Use binary search to find the minimum eating speed by searching between 1 and the maximum pile size, checking the feasibility of each mid-speed.

  • Time complexity: O(n * log m)
  • Space complexity: O(1)

where n is the length of the input array piles and m is the maximum number of bananas in a pile.

Code

More Articles