Koko eating bananas

Binary Search On answers Medium
  • This problem is based on Binary Search, an algorithm which is extensively used in real world applications
  • It presents a system with limited resources (the monkey and time) and seeks to optimize consumption (bananas)
  • This is a common scenario in software design
  • For example, when dealing with job scheduling in Computer Systems, where there are 'n' number of tasks and a limited processing power, system designers have to allocate resources in a way to get minimum execution time
  • Similarly, in Databases, index searching for a particular record is optimized using Binary Search
  • Which is the same concept of finding the minimum (or optimal) number to improve efficiency

A monkey is given n piles of bananas, where the 'ith' pile has nums[i] bananas. An integer h represents the total time in hours to eat all the bananas.


Each hour, the monkey chooses a non-empty pile of bananas and eats k bananas. If the pile contains fewer than k bananas, the monkey eats all the bananas in that pile and does not consume any more bananas in that hour.


Determine the minimum number of bananas the monkey must eat per hour to finish all the bananas within h hours.

Examples:

Input: n = 4, nums = [7, 15, 6, 3], h = 8

Output: 5

Explanation: If Koko eats 5 bananas/hr, he will take 2, 3, 2, and 1 hour to eat the piles accordingly. So, he will take 8 hours to complete all the piles.  

Input: n = 5, nums = [25, 12, 8, 14, 19], h = 5

Output: 25

Explanation: If Koko eats 25 bananas/hr, he will take 1, 1, 1, 1, and 1 hour to eat the piles accordingly. So, he will take 5 hours to complete all the piles.

Input: n = 4, nums = [3, 7, 6, 11], h = 8

Constraints

  •   1 <= n <= 104
  •   n <= h <= 109
  •   1 <= nums[i] <= 109

Hints

  • The monkey must eat at least k bananas per hour to finish all the bananas in h hours. The task is to determine the smallest k that satisfies this condition. Eating k bananas per hour affects how quickly piles are depleted, and k must balance speed and efficiency.
  • "The range for k is between 1 and max(nums). Perform binary search to find the smallest k: For each k, calculate the total hours required to eat all bananas."

Company Tags

Shopify Chewy NVIDIA Deloitte Cloudflare Johnson & Johnson Walmart Ubisoft Twilio MongoDB Intel Nutanix McKinsey & Company Etsy Ernst & Young JPMorgan Chase Medtronic Zoho Morgan Stanley Texas Instruments GE Healthcare Lyft AMD DoorDash Mastercard Google Microsoft Amazon Meta Apple Netflix Adobe