01
Problem Statement
You have n flowers; flower i blooms on day bloomDay[i]. You need to make m bouquets. To make one bouquet you need k adjacent flowers that have all bloomed. Return the minimum number of days you need to wait so that you can make at least m bouquets. If it is impossible (e.g. n < m * k), return -1.
- On day
d, a floweriis bloomed ifbloomDay[i] <= d. We can only use adjacent bloomed flowers to form a bouquet (each bouquet useskconsecutive bloomed flowers). We want the smallestdsuch that we can formmsuch bouquets. - Binary search on
d: For a candidate daymid, count how many bouquets we can make (scan for contiguous bloomed segments of length>= k, each segment contributessegmentLen / kbouquets). Ifcount >= m, we can try a smaller day (high = mid); elselow = mid + 1.
02
Key Observations
- For day
d, flowers withbloomDay[i] <= dare bloomed. We need contiguous segments of bloomed flowers; each segment of lengthLgivesL / kbouquets (integer division). Total bouquets = sum over segments of(segment length / k). Iftotal >= m, daydworks. - Binary search
din[min(bloomDay), max(bloomDay)](or[1, max]). Ifm * k > n, return -1.
03
Approach
High-level: If m * k > bloomDay.length return -1. Binary search day in [min(bloomDay), max(bloomDay)]. For each mid, count bouquets: scan array, when bloomDay[i] <= mid count contiguous bloomed length; when we have >= k contiguous, add length/k bouquets. If count >= m, high = mid; else low = mid + 1. Return low.
Steps:
- If
(long) m * k > bloomDay.lengthreturn -1.low = min(bloomDay),high = max(bloomDay). Whilelow < high:mid = low + (high - low) / 2. Count bouquets at daymid(contiguous bloomed segments, each segment contributeslen/k). Ifcount >= m,high = mid; elselow = mid + 1. - Return
low.
04
Implementation
Java
public int minDays(int[] bloomDay, int m, int k) {
if ((long) m * k > bloomDay.length) {
return -1;
}
int low = 1, high = (int) 1e9;
while (low < high) {
int mid = low + (high - low) / 2;
int bouquets = 0, streak = 0;
for (int d : bloomDay) {
streak = d <= mid ? streak + 1 : 0;
if (streak == k) { bouquets++; streak = 0; }
}
if (bouquets >= m) {
high = mid;
}
else {
low = mid + 1;
}
}
return low;
}05
Test Cases
Example 1
Input
bloomDay = [1,10,3,10,2], m = 3, k = 1
Expected
3Explanation
Day 3: all bloomed, 3 bouquets of 1.
06
Complexity Analysis
- Time: O(n log(max(bloomDay))).
- Space: O(1).
07
Follow-ups
- Similar: minimum time to complete with contiguous segments.