1482. Minimum Number of Days to Make m Bouquets

T: O(n*logn)
S: O(1)
class Solution {
    public int minDays(int[] bloomDay, int m, int k) {
        int n = bloomDay.length;
        if (m*k > n) {
            return -1;
        }
        int left = 1000000000;
        int right = 1;
        for (int i = 0; i < n; i++) {
            left = Math.min(left, bloomDay[i]);
            right = Math.max(right, bloomDay[i]);
        }

        while (left <= right) {
            int mid = left + (right - left)/2;
            if (ableToMakeBouquests(bloomDay, m, k, mid)) {
                if (mid - 1 >= 0 && !ableToMakeBouquests(bloomDay, m, k, mid-1)) { // check is that out of boundary
                    return mid;
                }
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }
    private boolean ableToMakeBouquests(int[] bloomDay, int m, int k, int days) {
        int count = 0;
        int bouquests = 0;
        for (int i = 0; i < bloomDay.length; i++) {
            if (days >= bloomDay[i]) {
                count++;
            } else {
                count = 0;
            }
            if (count == k) {
                bouquests++;
                count = 0;
            }
        }
        return bouquests >= m;
    }
}

/**

m * consequtive k -> find max value

k size win

with more days, we can get more flowers

check day is >= bloomDay is n
and we have logn days to check ->
so T: O(n*logn)
S: O(1)
 */

Last updated