MediumBinary SearchArrayGreedy

Koko Eating Bananas

LeetCode
1 approach, code in all languages

You are given a list of banana piles, where the value at each position tells you how many bananas sit in that pile. You also have a deadline of h hours before the piles are taken away. Each hour you pick a single pile and eat up to a fixed speed of k bananas from it; if the pile has fewer than k bananas left you finish it and idle for the rest of that hour, but you never switch to a second pile within the same hour.

Your goal is to find the smallest whole-number speed k that still lets you clear every pile within h hours. Larger speeds always make the job easier, so the answer is the exact point where 'just fast enough' begins.

Example 1

Input: piles = [3,6,7,11], h = 8

Output: 4

At speed 4 the piles take 1 + 2 + 2 + 3 = 8 hours, exactly meeting the deadline. Speed 3 would need 1 + 2 + 3 + 4 = 10 hours, which is too slow.

Example 2

Input: piles = [30,11,23,4,20], h = 5

Output: 30

There are 5 piles and only 5 hours, so each pile must be cleared in a single hour. The speed therefore has to be at least the size of the largest pile, which is 30.

Constraints

  • 1 <= piles.length <= 10^4
  • piles.length <= h <= 10^9
  • 1 <= piles[i] <= 10^9
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now