![]() |
VOOZH | about |
Given a garden with n different flowers and an array arr[], where ith flower will bloom after arr[i] days. To create one bouquet, you need to pick k adjacent flowers from the garden. You want to make a total of m bouquets. Find the minimum number of days you need to wait to make m bouquets from the garden. If it's impossible to create m bouquets, return -1.
Examples:
Input: m = 3, k = 2, arr[] = [3, 4, 2, 7, 13, 8, 5]
Output: 8
Explanation: We need 3 bouquets and each bouquet should have 2 flowers. After day 8: [x, x, x, x, _, x, x], we can make first bouquet from the first 2 flowers, second bouquet from the next 2 flowers and the third bouquet from the last 2 flowers.Input: m = 2, k = 3, arr[] = [5, 5, 5, 5, 10, 5, 5]
Output: 10
Explanation: We need 2 bouquets and each bouquet 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, taking 3 adjacent flowers in one bouquet.Input: m = 3, k = 2, arr[] = [1, 10, 3, 10, 2]
Output: -1
Explanation: As 3 bouquets each having 2 flowers are needed, that means we need 6 flowers. But there are only 5 flowers so it is impossible to get the needed bouquets therefore -1 will be returned.
Table of Content
The idea is to iterate over all possible days d starting from 0 to largest bloom day. To find whether it is possible to make m bouquets in d days, we traverse the array arr[] and check if there is at least m contiguous subarrays of size k such that each subarray has element <= d.
10
The idea is to use Binary search on answer. Our search space would be 0 to largest bloom day of flower, which represent the range in which minimum number of required days will lie. Now, calculate mid and check if mid days is possible to make m bouquet, such that k bloomed adjacent flowers can be selected to make a bouquet.
=> If possible then update the result with mid value and move towards lesser values in search space by updating high to mid - 1.
=> Otherwise, move towards larger values in search space by updating low to mid + 1.
10
Time complexity: O(n × log(maxDays)), where n is the number of elements in the array, and maxDays is the maximum possible number of days for a flower to bloom.
Auxiliary Space: O(1)