Minimum Number of Days to Make m Bouquets

Find the first day on which m bouquets of k neighbouring flowers can be made, by binary searching over the days.

A garden has n flowers in a row, and flower i blooms on day bloomDay[i] and stays open after that. A bouquet takes k bloomed flowers that stand next to each other in the row, and each flower can go into only one bouquet. Return the smallest number of days to wait before m bouquets can be made, or -1 if that never happens.

Example 1
Input: bloomDay = [1, 10, 3, 10, 2], m = 3, k = 1
Output: 3
Explanation: by day 3, the flowers that bloom on days 1, 3 and 2 are open: three bouquets of one flower.
Example 2
Input: bloomDay = [1, 10, 3, 10, 2], m = 3, k = 2
Output: -1
Explanation: 3 bouquets of 2 flowers need 6 flowers, and there are only 5.
Example 3
Input: bloomDay = [7, 7, 7, 7, 12, 7, 7], m = 2, k = 3
Output: 12
Explanation: on day 7 the flower that blooms on day 12 is still closed and splits the row, so only one bouquet fits. On day 12 every flower is open and two bouquets fit.
Solution

The Idea

Picture the seven plants of Example 3 along a garden path. Six of them bloom on day 7, and the fifth one blooms on day 12. You want 2 bouquets of 3 flowers each, and the 3 flowers of a bouquet must stand side by side. On day 7, six flowers are open, which sounds like exactly enough. But are they side by side?

Look at the picture below. In the row labelled day 7, the closed flower with bloom day 12 sits in the middle of the path. The four open flowers to its left give bouquet 1, with one flower left over, and the two open flowers to its right are one short of a bouquet. So day 7 gives only 1 bouquet.

The garden 7, 7, 7, 7, 12, 7, 7 with m = 2 and k = 3. On day 7 the flower with bloom day 12 is closed, so only bouquet 1 fits. On day 12 every flower is open and bouquets 1 and 2 fit. Asked whether 2 bouquets can be made by each day, days 7 to 11 say no and day 12 says yes.

In the row labelled day 12, the flower with bloom day 12 is open too. Together with the two flowers after it, it makes bouquet 2. So the answer is 12, and the question is how to find such a day in general.

Checking one day is easy: walk along the row and count the bouquets. Checking every day from the first bloom to the last can be slow, though. If the last flower blooms on day 1,000,000,000, that could mean a billion walks along the row.

Now look at the bottom row of the picture, labelled "2 bouquets by this day?". For days 7 to 11 the answer is no, and for day 12 it is yes. A flower that has opened stays open, so a later day never has fewer open flowers, and never fewer bouquets. Once the answer turns to yes, it stays yes for every later day.

That shape lets us skip most days. Try a day in the middle of the range. A yes means the first yes is that day or earlier, so the later days can be dropped. A no means the first yes comes later, so that day and the earlier ones can be dropped. Each check halves the days still in play. This halving is binary search, run here over days rather than over the positions of a sorted array.

Solution Approach

Turning that idea into code means settling four things: when the answer is -1, how to count the bouquets on one day, which days to search, and how to halve the range without skipping the first yes.

When no day is enough

Can waiting ever fail, when every flower blooms in the end? Yes: m bouquets of k flowers need m × k flowers. Example 2 asks for 3 bouquets of 2, which is 6 flowers from a garden of 5. Waiting adds no flowers, so the answer is -1 straight away.

If the garden has enough flowers, the last bloom day always works: every flower is open, nothing breaks the row, and the m bouquets can be cut one after another from the left. The check itself needs care, though. A request for a million bouquets of 100,000 flowers makes m × k equal to 1011, far more than a Java int can store. Computed as an int, it wraps around to a wrong value, so the code computes it as a long.

Counting bouquets on one day

How do we count the bouquets for a given day? A flower is open when bloomDay[i] <= day. Walk along the row and keep run, the number of open flowers in a row so far. When run reaches k, that makes one bouquet: count it and set run back to 0, because those flowers are used up. A closed flower also sets run to 0, because no bouquet can reach across it.

Taking a bouquet as soon as a run reaches k never costs one later: using the leftmost open flowers leaves as many as possible for the rest of the row. Counting all open flowers and dividing by k does not work, though. On day 7, Example 3 has six open flowers, and six divided by 3 suggests two bouquets, but the picture shows only one fits.

The range of days to search

Which days can be the answer? Before the earliest bloom day nothing is open, so no bouquet can be made. On the latest bloom day everything is open, and that day works whenever the garden has enough flowers. So the search runs from the smallest value in bloomDay, called lo, to the largest, called hi. For Example 3 that is day 7 to day 12.

Halving the range

How do we halve the range without skipping the first yes? Keep the answer always between lo and hi, and take the day mid halfway between them. If day mid gives at least m bouquets, it works, so the answer is mid or earlier: set hi = mid, which keeps mid in the range. Otherwise the answer is later: set lo = mid + 1. When lo and hi meet, they sit on the answer.

In Example 3, lo is 7 and hi is 12. Day 9 gives 1 bouquet, so lo becomes 10. Day 11 gives 1 bouquet too, so lo becomes 12 and meets hi. Only two days were checked, not six.

The middle day is written lo + (hi - lo) / 2 rather than (lo + hi) / 2. Both give the same day, but adding two large bloom days could go past what an int can store, while the gap between them always fits.

Java Solution

The method minDays works in these steps:

  1. First, check the number of flowers: if (long) m * k is more than bloomDay.length, return -1.
  2. Find the range with one loop over bloomDay: lo becomes the earliest bloom day and hi the latest.
  3. While lo is less than hi, take the middle day mid and ask the helper method bouquetsOnDay how many bouquets fit on that day. If the count is at least m, set hi = mid; otherwise set lo = mid + 1.
  4. Inside bouquetsOnDay, a loop walks the row once with two counters: run for open flowers in a row and bouquets for bouquets made. A full run adds a bouquet and resets run, and a closed flower resets it too.
  5. When lo and hi meet, return lo, the first day with enough bouquets.

The main method runs the three examples and prints the bouquet counts of Example 3 on days 7, 11 and 12. Then it tries a garden where every flower is needed, and a request whose m × k does not fit in an int.

Java
public class MinimumDaysForBouquets {

    public static int minDays(int[] bloomDay, int m, int k) {
        if ((long) m * k > bloomDay.length) {
            return -1;                         // not enough flowers, whatever the day
        }
        int lo = Integer.MAX_VALUE;
        int hi = 0;
        for (int d : bloomDay) {
            lo = Math.min(lo, d);              // nothing blooms earlier
            hi = Math.max(hi, d);              // everything has bloomed by then
        }
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (bouquetsOnDay(bloomDay, mid, k) >= m) {
                hi = mid;                      // mid works: the answer is mid or earlier
            } else {
                lo = mid + 1;                  // mid is too early
            }
        }
        return lo;
    }

    // Count bouquets of k adjacent bloomed flowers that can be made on 'day'
    static int bouquetsOnDay(int[] bloomDay, int day, int k) {
        int bouquets = 0;
        int run = 0;                           // bloomed flowers in a row so far
        for (int d : bloomDay) {
            if (d <= day) {
                run++;
                if (run == k) {
                    bouquets++;
                    run = 0;                   // these k flowers are used up
                }
            } else {
                run = 0;                       // a flower that has not bloomed breaks the run
            }
        }
        return bouquets;
    }

    public static void main(String[] args) {
        System.out.println(minDays(new int[] {1, 10, 3, 10, 2}, 3, 1));
        System.out.println(minDays(new int[] {1, 10, 3, 10, 2}, 3, 2));
        int[] garden = {7, 7, 7, 7, 12, 7, 7};
        System.out.println(minDays(garden, 2, 3));
        System.out.println("day 7: " + bouquetsOnDay(garden, 7, 3)
            + ", day 11: " + bouquetsOnDay(garden, 11, 3)
            + ", day 12: " + bouquetsOnDay(garden, 12, 3));
        System.out.println(minDays(new int[] {5, 1, 3}, 1, 3));
        System.out.println(minDays(new int[] {1, 10, 3, 10, 2}, 65536, 65536));
    }
}

Running it prints:

Output
3
-1
12
day 7: 1, day 11: 1, day 12: 2
5
-1

Examples 1 to 3 print 3, -1 and 12, and the -1 comes from the flower count alone, before any day is checked. The fourth line backs up the picture. Example 3 makes 1 bouquet on day 7, still 1 on day 11, the last day the search checked, and 2 on day 12.

The fifth line comes from [5, 1, 3] with m = 1 and k = 3. The one bouquet needs all three flowers, so the answer is the latest bloom day, 5, which is hi itself.

The last line, -1, is the product check. 65,536 × 65,536 is 4,294,967,296, and multiplied as an int it wraps around to exactly 0. A version with an int product passes the check, never finds a day with enough bouquets, and prints 10, the latest bloom day. The long product sees that 5 flowers are far too few.

Complexity

The work is one pass to find the range, then one walk along the row for every day the search checks.

  • Time: O(n log D), where D is the number of days from the earliest bloom day to the latest. Each check halves the days still in play, so there are about log2 D checks, and each walks all n flowers.
  • Space: O(1). The search keeps lo, hi and mid, the walk keeps run and bouquets, and the array is never copied.

Koko Eating Bananas has the same shape, with eating speeds in place of days.