Leetcode 875: Koko Eating Bananas

grid47
grid47
Exploring patterns and algorithms
Aug 11, 2024 6 min read

Koko loves to eat bananas and there are multiple piles of bananas. Each pile has a certain number of bananas. Koko can decide how many bananas she wants to eat per hour, and each hour she can choose any pile to eat from. If the pile contains fewer bananas than her chosen rate, she finishes that pile and moves to another pile. Koko needs to finish all the bananas before the guards return in h hours. You need to determine the minimum number of bananas per hour Koko should eat in order to finish all piles within the given time.
Problem
Approach
Steps
Complexity
Input: The input consists of a list of integers where each integer represents the number of bananas in a pile, and an integer h representing the total hours Koko has to finish the bananas.
Example: Input: piles = [4, 10, 7, 13], h = 6
Constraints:
• 1 <= piles.length <= 10^4
• piles.length <= h <= 10^9
• 1 <= piles[i] <= 10^9
Output: Return the minimum integer k such that Koko can eat all the bananas within h hours. If no such integer exists, return 0.
Example: Output: 8
Constraints:
• The output should be a single integer representing the minimum speed Koko needs to eat the bananas.
Goal: The goal is to find the minimum number of bananas per hour, k, that allows Koko to eat all the bananas within h hours.
Steps:
• Perform a binary search on the possible eating speeds from 1 to the maximum number of bananas in any pile.
• For each candidate eating speed k, calculate the total number of hours Koko would take to eat all piles at that speed.
• If the total hours exceed h, increase the speed; otherwise, try a smaller speed until you find the minimum k.
Goal: The solution should handle a variety of pile sizes and eating speeds efficiently.
Steps:
• 1 <= piles.length <= 10^4
• piles.length <= h <= 10^9
• 1 <= piles[i] <= 10^9
Assumptions:
• The input array piles is non-empty and contains positive integers.
• Koko's eating speed is adjustable and the goal is to minimize it while ensuring all bananas are eaten within h hours.
Input: Input: piles = [4, 10, 7, 13], h = 6
Explanation: The minimum speed Koko needs to eat all bananas in 6 hours is 8 bananas per hour, as at this speed she can finish all piles within the given time.

Input: Input: piles = [5, 15, 12, 30], h = 4
Explanation: The minimum speed Koko needs to eat all bananas in 4 hours is 15 bananas per hour.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus