
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Minimum Number of Days to Make M Bouquets Using Python
Suppose we have an array with integers called nums, we also have another two values m and k. Now, we need to make m bouquets. To make one bouquet we need k adjacent flowers from the garden. Here the garden consists of n different flowers, the ith flower will bloom in the bloomDay[i]. Each flower can be used inside only one bouquets. We have to find the minimum number of days need to wait to make m bouquets from the garden. If we cannot make m bouquets, then return -1.
So, if the input is like bloomDay = [5,5,5,5,10,5,5] m = 2 k = 3, then the output will be 10 because we need 2 (m = 2) bouquets and each should have 3 flowers.
After day 5: [x, x, x, x, _, x, x], we can make one bouquet of the first three flowers that bloomed, but cannot make another bouquet
After day 10: [x, x, x, x, x, x, x], Now we can make two bouquets in different ways.
To solve this, we will follow these steps −
n := size of bloomDay
-
if m * k > n, then
return -1
Define a function possible() . This will take x
count := 0, bouquets := 0
-
for each d in bloomDay, do
-
if d <= x, then
count := count + 1
-
if count is same as k, then
bouquets := bouquets + 1
count := 0
-
otherwise,
count := 0
-
return true if bouquets >= m, otherwise false
From the main method do the following −
left := 0, right := 1 + maximum of bloomDay
-
while left < right, do
mid :=(left + right) /2
-
if possible(mid) is true, then
right := mid
-
otherwise,
left := mid + 1
-
if possible(left) is true, then
return left
otherwise return left + 1
Let us see the following implementation to get better understanding −
Example
def solve(bloomDay, m, k): n = len(bloomDay) if m * k > n: return -1 def possible(x): count = 0 bouquets = 0 for d in bloomDay: if d <= x: count += 1 if count == k: bouquets += 1 count = 0 else: count = 0 return bouquets >= m left, right = 0, max(bloomDay) + 1 while left < right: mid = (left + right)//2 if possible(mid): right = mid else: left = mid + 1 if possible(left): return left else: return left + 1 bloomDay = [5,5,5,5,10,5,5] m = 2 k = 3 print(solve(bloomDay, m, k))
Input
[5,5,5,5,10,5,5], 2, 3
Output
10