Minimum Number of Days to Make m Bouquets
LeetCode 1482 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Bouquets(day) is monotonic ⇒ binary search the day.
मी Minimum Number of Days to Make m Bouquets (LeetCode 1482) असा सोडवला — Binary Search on Answer पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि 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.
मी कसा सोडवला
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 — वारंवार विचारले जाणारे प्रश्न
Minimum Number of Days to Make m Bouquets मागील 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.
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.
Minimum Number of Days to Make m Bouquets ची time आणि space complexity किती आहे?
Time: O(n log D). Space: O(1). (Accepted approach: Binary search on days.)
Minimum Number of Days to Make m Bouquets मध्ये सामान्य चुका कोणत्या?
Reset the run counter after forming a bouquet and on unbloomed flowers.