1. Impossible check
Not enough flowers for m bouquets of k means -1.
if (m * k > bloomDay.length) {
return -1;
}Typorithm · medium
Step 1 of 8 · intro card
Binary Search on Answer
Binary search the day; feasibility counts bouquets from runs of k adjacent bloomed flowers, minimizing the day.
By a given day, a flower is usable if it has bloomed, and a bouquet needs k ADJACENT bloomed flowers.
Binary search the day between the earliest and latest bloom; count bouquets greedily from adjacency runs.
If at least m bouquets form, search an earlier day; otherwise a later one.
Bouquet = k adjacent bloomed flowers.
A gap resets the run.
Minimize the day with >= m bouquets.
function minDays(bloomDay, m, k) {
if (m * k > bloomDay.length) {
return -1;
}
let lo = Math.min(...bloomDay);
let hi = Math.max(...bloomDay);
while (lo < hi) {
const mid = (lo + hi) >> 1;
let bouquets = 0;
let flowers = 0;
for (const day of bloomDay) {
if (day <= mid) {
flowers += 1;
if (flowers === k) {
bouquets += 1;
flowers = 0;
}
} else {
flowers = 0;
}
}
if (bouquets >= m) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}Connect each part of the code to the concept before you type.
Not enough flowers for m bouquets of k means -1.
if (m * k > bloomDay.length) {
return -1;
}Search days between the earliest and latest bloom.
let lo = Math.min(...bloomDay)k ADJACENT bloomed flowers form one bouquet.
if (flowers === k) {
bouquets += 1;
flowers = 0;
}An unbloomed flower resets the adjacency run.
} else {
flowers = 0;
}Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.