Minimum Number of Days to Make m Bouquets
LeetCode 1482 · Medium · solution, intuition & step-by-step walkthrough
Bouquets(day) is monotonic ⇒ binary search the day.
This is how I solved Minimum Number of Days to Make m Bouquets (LeetCode 1482), a medium problem from the Binary Search on Answer pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Once a flower blooms it stays bloomed, so the number of bouquets you can make only grows with the day. Binary search the earliest day on which you can collect m groups of k adjacent bloomed flowers.
Approach
- 1
Impossible if m·k exceeds the number of flowers.
- 2
For a day, scan and count runs of bloomed flowers; every k in a row makes a bouquet.
- 3
Enough bouquets → search earlier; else later.
How I solved it
Binary search on daysPythonO(n log D) time
#leetcode editorial
"""
we observe a crucial property: once a flower blooms, it remains bloomed. This means that the number of bloomed flowers stays the same or increases as the days progress. The same goes for the number of bouquets that can possibly be made.
"""
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
if len(bloomDay)<m*k:
return -1
def getNOfBouquets(mid):
bouquets=0
count=0
for day in bloomDay: #n
#if the flower was already blosommed or blosomosed on the day we can add count
if day<=mid:
count+=1
else:
count=0
if count==k: #consequitive days
bouquets+=1
count=0
return bouquets
low = 1 #day 10
high = max(bloomDay) #max day
while(low<=high):
mid = (low+high)//2 #logD
noofBouquets=getNOfBouquets(mid)
if noofBouquets>=m:
high= mid-1 #look for min days
else:
low = mid+1
return low
Minimum Number of Days to Make m Bouquets — FAQ
What is the intuition behind Minimum Number of Days to Make m Bouquets?
Once a flower blooms it stays bloomed, so the number of bouquets you can make only grows with the day. Binary search the earliest day on which you can collect m groups of k adjacent bloomed flowers.
How do you solve Minimum Number of Days to Make m Bouquets (LeetCode 1482)?
1. Impossible if m·k exceeds the number of flowers. 2. For a day, scan and count runs of bloomed flowers; every k in a row makes a bouquet. 3. Enough bouquets → search earlier; else later.
What is the time and space complexity of Minimum Number of Days to Make m Bouquets?
Time: O(n log D). Space: O(1). (Accepted approach: Binary search on days.)
What are common mistakes in Minimum Number of Days to Make m Bouquets?
Reset the run counter after forming a bouquet and on unbloomed flowers.