AlgoInsight

DSA problem

Minimum Number of Days to Make m Bouquets

MediumBinary SearchPattern: Binary Searchtop600AmazonGoogleMicrosoft

You are given an integer array bloomDay, an integer m, and an integer k. You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden has n flowers; the i-th flower will bloom in the bloomDay[i]-th day and then can be used in any bouquet. Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.

Like Koko and Ship Capacity, this is binary search the answer. Define canMake(day) = "on day day, can we form at least m bouquets?" The predicate is monotonic: if day suffices, every later day also suffices. So the valid days form a suffix, and binary searching the boundary gives the answer.

The predicate runs a single linear scan of bloomDay. Walk left to right, counting the current run of consecutive bloomed (bloomDay[i] <= day) flowers; whenever the run reaches k, count one bouquet and reset the run. Return whether the bouquet count reached m.

The search range for day is [min(bloomDay), max(bloomDay)]. The lower bound is the earliest any flower blooms; the upper bound is the latest. If m * k > n, return -1 immediately because not enough flowers can ever bloom. Use the lower-bound shape: lo = min(bloomDay), hi = max(bloomDay), narrow hi to mid when canMake(mid). Time O(n log(max - min)), space O(1).

Examples

Example 1
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: On day 3 the bloomed flags are [T, F, T, F, T] giving 3 isolated bloomed flowers, each a length-1 bouquet for a total of 3.
Example 2
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: Even on the last day, only 5 flowers exist and we need 3 × 2 = 6 adjacent ones — impossible.
Example 3
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: Before day 12 only the first 4 plus the last 2 form a 4-run and a 2-run — only one bouquet of length 3 fits. On day 12 the 7th flower also blooms and forms a second bouquet.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-searcharraybinary-search-the-answergreedy

Browse all DSA problems