Typorithm · medium

Minimum Days for Bouquets

min-days-bouquetsbinary-search-answeranswer-spaceadjacent-runfeasibility
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Minimum Days for Bouquets

0%

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.

01

Bouquet = k adjacent bloomed flowers.

02

A gap resets the run.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Impossible check

Not enough flowers for m bouquets of k means -1.

if (m * k > bloomDay.length) {
    return -1;
  }

2. Day range

Search days between the earliest and latest bloom.

let lo = Math.min(...bloomDay)

3. Complete a bouquet

k ADJACENT bloomed flowers form one bouquet.

if (flowers === k) {
          bouquets += 1;
          flowers = 0;
        }

4. Run broken

An unbloomed flower resets the adjacency run.

} else {
        flowers = 0;
      }

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Minimum Days for Bouquets: Lesson & Practice · Typorithm | ApplyDjinn