Leetcode1482. Minimum Number of Days to Make m Bouquets [Medium] Python Binary Search

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:

Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.

Example 4:

Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.

Example 5:

Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9

一道中等难度的题但是看起来也是手足无措,其实想一想,这个几束花和多少花之间,哪个变量容易控制?这是思路的起点,也就是说,要么我控制一定要多少束花,但是看看要连续多少花符合这样的要求,或者说一定要多少花,看看能组合成多少花束。

 

很显然后者难度更小一点,因为我们都是扫描一遍数组,规定了一定要多少花,如果花的数量满足了,个么花束就多一束,一直扫描结束,看看能组成多少花束。这样讲还是很抽象,直接讲答案。有的时候你知道答案反过来推思路会发现清晰无比,但是不知道答案的时候的时候你怎么想都想不到的。

 

答案还是二分法,我觉得吧应该看到题目有感觉,这是一道binary search, 但凡问你多少天多少量比较合适,就应该 想到二分法了。有了二分法的答案,再回答最上面,到底是控制花束还是控制花的量,显而易见了,你扫描数组,如果小于你的预设值,个么花加1,花加到k值了,花束就加1,扫描结束看看能弄到多少花束,如果大于要求的花束了,代表你预制大了,可以少等几天,如果少于要求,那么你就要多等几天。

代码:

class Solution:
    def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
        if len(bloomDay) < m*k:
            return -1
        
        l=min(bloomDay)
        r=max(bloomDay)
        
        while l=k:
                        bouquets+=flowers//k
                        flowers=flowers%k
                else:
                    flowers=0
            if bouquets

corner case:

当花束和花的要求比你有的花还多显然不能完成任务

tricky part

就是当你连续很多很多很多很多的花都小于预设值,其实你一下子很大包老多花束了,这也是就是为什么就flower//k 而不是加1, 然后你打包了几束花可能还是剩了几只花,所以flowers= flowers%k 这个很巧妙

 

 

你可能感兴趣的:(python,leetcode)