Minimum Number of Days to Make m Bouquets
Difficulty: Medium · Pattern: Binary Search · LeetCode #1482
bloomDay[i] is the day flower i blooms. A bouquet needs k adjacent bloomed flowers. Return the minimum day on which you can make m bouquets, or −1 if impossible.
Examples
text
bloomDay = [1, 10, 3, 10, 2], m = 3, k = 1 → 3
bloomDay = [1, 10, 3, 10, 2], m = 3, k = 2 → −1
bloomDay = [7, 7, 7, 7, 12, 7, 7], m = 2, k = 3 → 12Hints
- If m·k > n, it's impossible.
- If day d works, any later day works. Binary search d over the bloom days.
Approach
can(d): scan the flowers, counting consecutive bloomed ones (bloomDay ≤ d); each run of k makes a bouquet (reset the run). Binary search the smallest d in [min, max] with can(d) true. O(n log(max)).
Complexity
Time: O(n · log(max)). Space: O(1).
Python solution
def minDays(bloomDay, m, k):
if m * k > len(bloomDay):
return -1
def can(day):
bouquets = run = 0
for b in bloomDay:
if b <= day:
run += 1
if run == k:
bouquets += 1; run = 0
else:
run = 0
return bouquets >= m
lo, hi = min(bloomDay), max(bloomDay)
while lo < hi:
mid = (lo + hi) // 2
if can(mid): hi = mid
else: lo = mid + 1
return loJavaScript solution
function minDays(bloomDay, m, k) {
if (m * k > bloomDay.length) return -1;
const can = (day) => { let b = 0, run = 0; for (const d of bloomDay) { if (d <= day) { if (++run === k) { b++; run = 0; } } else run = 0; } return b >= m; };
let lo = Math.min(...bloomDay), hi = Math.max(...bloomDay);
while (lo < hi) { const mid = Math.floor((lo + hi) / 2); if (can(mid)) hi = mid; else lo = mid + 1; }
return lo;
}