Binary Search · Medium

Minimum Eating Speed to Finish All Fruit Piles in Time

Solve it on DeVert Campus - free code runner

Problem

There are n piles of fruit in a row, the i-th pile containing piles[i] fruits. You must finish eating all the fruit within h hours. Each hour you choose one pile and eat up to k fruits from it, where k is a single fixed eating speed chosen before you start and used for the whole process; if a pile has fewer than k fruits left, you finish it during that hour and do not touch another pile until the next hour. Find the minimum integer value of k that lets you finish every pile within h hours.

Input and output

Input: The first line contains two integers n and h. The second line contains n space-separated integers, the sizes of the piles. Output: Print a single integer: the minimum eating speed k.

Example

Input:
4 8
3 6 7 11
Output:
4

Constraints

1 <= n <= 10^4 1 <= piles[i] <= 10^9 n <= h <= 10^9

Key observation

This is a textbook example of the 'minimize the maximum resource such that a monotonic feasibility condition holds' binary-search-on-answer pattern - recognizing the shared structure across many superficially different real-world-sounding problems is the key transferable skill.

Intuition

Find the slowest possible constant eating speed that still finishes every fruit pile within a time limit. Brute force: Try every possible speed starting from 1 upward, checking feasibility for each, until finding the first one that works - this costs O(max pile size * n), too slow when pile sizes can be up to 10^9. Optimised: Since the total hours needed is a MONOTONIC (non-increasing) function of the eating speed k, binary searching directly on k - checking feasibility with an O(n) sum of ceiling divisions at each candidate - narrows down to the exact minimum speed in O(n log(max pile size)), far faster than trying every possible speed one at a time.

Step by step

1. Recognize that the SLOWEST workable speed is 1, and the FASTEST you'd ever need is the size of the single largest pile - binary search that range. 2. For a candidate speed k, compute the total hours needed: for each pile of size p, that's ceil(p / k) hours; sum this across every pile. 3. Since total hours needed only DECREASES as k increases (a monotonic relationship), binary search for the SMALLEST k whose total hours is <= h.

Complexity

Time: O(n log(max pile size)) - each of the O(log(max pile size)) binary search steps costs O(n) to check feasibility. Space: O(1) extra space beyond the input array.

Edge cases

h exactly equal to n forces the maximum possible speed (only one hour is available per pile, so k must clear even the largest pile in a single hour); a single pile (n = 1).

Interview tip

Be ready to recognize this as yet another instance of 'binary search on the answer' - the exact same pattern as Eko/Painter's Partition/Book Allocation, just with a different feasibility formula (ceiling division summed across piles).

All DSA problems