Binary search on days. The feasibility check — count consecutive bloomed flowers — is the only novel part.
You have n flowers in a row. bloomDay[i] is the day the i-th flower blooms. To make one bouquet you need k adjacent bloomed flowers. Return the minimum number of days to make m bouquets. Return -1 if impossible.
More days always means more bloomed flowers — so if day X works, day X+1 also works. Perfect monotonicity. Binary search over days 1..max(bloomDay). For each candidate day, greedily count how many bouquets of k consecutive bloomed flowers we can form.
Impossible case: If m * k > len(bloomDay), we can never have enough flowers regardless of how many days pass. Return -1 immediately — don't enter the binary search.
Feasibility function structure: Scan left-to-right. Track consecutive bloomed flowers. Every time you hit k consecutive, increment bouquets and reset the counter. If final bouquet count ≥ m, return true.
class Solution { public int minDays(int[] bloomDay, int m, int k) { if ((long) m * k > bloomDay.length) return -1; int left = 1, right = 0; for (int d : bloomDay) right = Math.max(right, d); int boundary = right; while (left <= right) { int mid = left + (right - left) / 2; if (canMake(bloomDay, mid, m, k)) { boundary = mid; right = mid - 1; } else { left = mid + 1; } } return boundary; } private boolean canMake(int[] bloomDay, int day, int m, int k) { int bouquets = 0, consecutive = 0; for (int d : bloomDay) { if (d <= day) { consecutive++; if (consecutive == k) { bouquets++; consecutive = 0; } } else { consecutive = 0; } } return bouquets >= m; } }
class Solution: def minDays(self, bloomDay: list[int], m: int, k: int) -> int: if m * k > len(bloomDay): return -1 left, right = 1, max(bloomDay) boundary = right while left <= right: mid = left + (right - left) // 2 if self.can_make(bloomDay, mid, m, k): boundary = mid right = mid - 1 else: left = mid + 1 return boundary def can_make(self, bloom_day, day, m, k): bouquets = consecutive = 0 for d in bloom_day: if d <= day: consecutive += 1 if consecutive == k: bouquets += 1 consecutive = 0 else: consecutive = 0 return bouquets >= m