Visualize

Pattern visualizer

Minimum Days to Make M Bouquets

The array is not sorted and sorting it would destroy the adjacency the bouquets depend on, so there is nothing here to binary search directly. What IS ordered is the calendar: a flower open on day 9 is still open on day 10, so the number of bouquets available never falls as the day rises. Feasibility flips from no to yes exactly once along that line, and binary search hunts that flip. Each guessed day is tested by one left-to-right walk that counts the current run of open flowers, cutting a bouquet every time the run reaches k and resetting the run at any flower still in bud. Animated on: bloomDay = [7,7,7,7,13,11,12,7], m = 2, k = 3 — each bouquet needs 3 ADJACENT flowers that have already bloomed; find the earliest day 2 bouquets can be made..

Binary search the day, scan adjacent runs to test it

time O(n log(max(bloomDay)))space O(1)step 1 / 9
7
[0]
7
[1]
7
[2]
7
[3]
13
[4]
11
[5]
12
[6]
7
[7]
line 4

Each cell is the day that flower opens. We need 2 bouquets of 3 ADJACENT flowers each, and picking one never blocks another, so the only question is which day to harvest. Nothing opens before day 7 and everything is open by day 13, so the answer lives in [7, 13].

Pseudocode
1FUNCTION minDays(bloom, m, k):
2 IF m * k > LENGTH(bloom):
3 RETURN -1
4 low <- MIN(bloom)
5 high <- MAX(bloom)
6 WHILE low < high:
7 mid <- (low + high) / 2
8 IF BOUQUETS(bloom, mid, k) >= m:
9 high <- mid
10 ELSE:
11 low <- mid + 1
12 RETURN low

← / → step · space play · Home restart

Where to practice Binary Search