Minimum Number of Days to Make m Bouquets
Problem (restated)
Garden blooms on bloomDay[i]. Make m bouquets of k adjacent flowers. Min days, or -1.
Intuition
If day d works, later days work. binary search d; greedy count bouquets on day d.
Approaches
Binary search day
UnverifiedIdea. lo=min(days), hi=max(days). canMake(d): scan adjacent groups of k blooms ≤ d.
Walkthrough. [1,10,3,10,2], m=3, k=1 → 3; m=3,k=2 → -1.
Trade-offs. Same feasibility pattern as ship/Koko.
export function minDays(bloomDay: number[], m: number, k: number): number {
if (BigInt(m) * BigInt(k) > BigInt(bloomDay.length)) return -1;
let lo = Math.min(...bloomDay), hi = Math.max(...bloomDay);
const ok = (day: number) => {
let bouquets = 0, adj = 0;
for (const d of bloomDay) {
if (d <= day) { adj++; if (adj === k) { bouquets++; adj = 0; } }
else adj = 0;
}
return bouquets >= m;
};
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (ok(mid)) hi = mid; else lo = mid + 1;
}
return lo;
}
export function minDays(bloomDay: number[], m: number, k: number): number {
if (BigInt(m) * BigInt(k) > BigInt(bloomDay.length)) return -1;
let lo = Math.min(...bloomDay), hi = Math.max(...bloomDay);
const ok = (day: number) => {
let bouquets = 0, adj = 0;
for (const d of bloomDay) {
if (d <= day) { adj++; if (adj === k) { bouquets++; adj = 0; } }
else adj = 0;
}
return bouquets >= m;
};
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (ok(mid)) hi = mid; else lo = mid + 1;
}
return lo;
}
Template connection
Binary search on the bloom day; greedy adjacent groups of k is the feasibility check.
Reflection
- On day
dyou needmbouquets ofkadjacent flowers that have bloomed.feasible(d)counts them in one pass. An unbloomed flower breaks the run. - If
m * k > n, return −1.lois the earliest bloom day,hithe latest. - If the flowers did not have to be adjacent, would this still be a binary search on the answer?