#1482
Minimum Number of Days to Make m Bouquets
MediumArrayBinary SearchBinary SearchGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log d) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log d)Space O(1)
Using binary search allows us to efficiently find the minimum day by checking if we can create the required bouquets on that day. This reduces the number of days we need to check.
⚙️
Algorithm
4 steps- 1Step 1: Check if it's possible to make m bouquets with k flowers each; if not, return -1.
- 2Step 2: Set up binary search between the minimum and maximum bloom days.
- 3Step 3: For each mid day in the binary search, check if we can make m bouquets.
- 4Step 4: Adjust the search range based on whether we can make the bouquets.
solution.py32 lines
1# Full working Python code
2
3def canMakeBouquets(bloomDay, m, k, days):
4 count = 0
5 bouquets = 0
6 for bloom in bloomDay:
7 if bloom <= days:
8 count += 1
9 if count == k:
10 bouquets += 1
11 count = 0
12 else:
13 count = 0
14 return bouquets >= m
15
16
17def minDays(bloomDay, m, k):
18 if len(bloomDay) < m * k:
19 return -1
20 left, right = 1, max(bloomDay)
21 while left < right:
22 mid = (left + right) // 2
23 if canMakeBouquets(bloomDay, m, k, mid):
24 right = mid
25 else:
26 left = mid + 1
27 return left
28
29bloomDay = [1,10,3,10,2]
30m = 3
31k = 1
32print(minDays(bloomDay, m, k))ℹ
Complexity note: The complexity is O(n log d) where n is the number of flowers and d is the maximum bloom day. We check each day in a binary search manner.
- 1If we can make m bouquets on day x, we can make them on any day after x.
- 2We need to ensure that the total number of flowers is sufficient to meet the bouquet requirements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.