1482. Minimum Number of Days to Make m Bouquets

Description

Given an integer array bloomDay, an integer m and an integer k.

We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.

The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.

Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.

Example 1:

Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _]   // we can only make one bouquet.
After day 2: [x, _, _, _, x]   // we can only make two bouquets.
After day 3: [x, _, x, _, x]   // we can make 3 bouquets. The answer is 3.

Example 2:

Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.

Example 3:

Example 4:

Example 5:

Constraints:

  • bloomDay.length == n

  • 1 <= n <= 10^5

  • 1 <= bloomDay[i] <= 10^9

  • 1 <= m <= 10^6

  • 1 <= k <= n

Tags

Array, Binary Search

Solution

Based on the hint that "If we can make m or more bouquets at day x, then we can still make m or more bouquets at day y, y > x.", we can perform the binary search strategy between the interval [min(bloomDay), max(bloomDay)]. We check if we can make at least m bouquets within mid = (start+end)/2 days. If we can, assign mid to end; otherwise let start = mid. After this loop, we also need to check if either start days or end days can make m bouquets. If both cannot, return -1.

Complexity

  • Time complexity: O(nlog(max(bloomDay)))O(n\log(\max(bloomDay)))

  • Space complexity: O(1)O(1)

Code

Last updated

Was this helpful?