Skip to content
DSA Patterns
Menu
Language
Binary Search on AnswerLC #14826 of 6← Previous

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

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

Unverified
Time O(n log D)Space O(1)

Idea. 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.

Solution
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

If m * k > n, there are not enough flowers, so the answer is -1. Otherwise search the day. A bouquet is k adjacent flowers already bloomed by that day. Fewer than m bouquets means the day is too early.

Reflection

  • On day d you need m bouquets of k adjacent flowers that have bloomed. feasible(d) counts them in one pass. An unbloomed flower breaks the run.
  • If m * k > n, return −1. lo is the earliest bloom day, hi the latest.
  • If the flowers did not have to be adjacent, would this still be a binary search on the answer?
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Bloom days [1,10,3,10,2]. Need m=3 bouquets of k=1 adjacent flower.

1
0
10
1
3
2
10
3
2
4

m=3, k=1

Key:MatchSettledEliminated