其他分享
首页 > 其他分享> > 【每日一题】1482. 制作 m 束花所需的最少天数

【每日一题】1482. 制作 m 束花所需的最少天数

作者:互联网

https://leetcode-cn.com/problems/minimum-number-of-days-to-make-m-bouquets/

通过题目可以发现,最终结果在最大值和最小值之间,另外,1 <= bloomDay[i] <= 10^9,可以考虑使用二分法解决这种类型的问题。
二分法对于数据量特别大的查找非常方便快捷,结果含有极值,满足二分法的使用条件。


class Solution {
    public int minDays(int[] bloomDay, int m, int k) {
        if(k * m > bloomDay.length){
            return -1;
        }
        int low = 1;
        int high = 1;
        int length = bloomDay.length;
        for(int i = 0; i < length; i++){
            high = Math.max(high, bloomDay[i]);
        }

        while(low < high){
            int days = (high - low) / 2 + low;
            if(canMake(bloomDay, m, k, days)){
                high = days;
            }
            else{
                low = days + 1;
            }
        }
        return low;
    }

    public boolean canMake(int[] bloomDay, int m, int k, int days){
        int len = bloomDay.length;
        int flowers = 0;
        int bouquets = 0;
        for(int i = 0; i < len && bouquets < m; i++){
            if(bloomDay[i] <= days){
                flowers ++;
                if(flowers == k){
                    bouquets ++;
                    flowers = 0;
                }
            }
            else{
                flowers = 0;
            }
        }
        return bouquets >= m;
    }
}

标签:int,天数,days,束花,high,1482,length,bloomDay,low
来源: https://www.cnblogs.com/realzhaijiayu/p/14747649.html