Online store~25 min2s · 256 MBtarget O(n log D) time, O(1) spaceclassic twin: lc-1482binary-search-answer
An online store sells flower bouquets. In the greenhouse, a row of buds will bloom, and the app knows the day each bud blooms. A bouquet needs k buds that sit next to each other in the row, and all of them must have bloomed.
The store wants m bouquets, and each bud can go into one bouquet only. On which day is the earliest that the store can make all m bouquets?
Write bloom_day(bloom, m, k).
bloom[i] is the day on which bud i blooms. From that day on, it stays bloomed.k buds that are next to each other in the row, all bloomed. A bud belongs to at most one bouquet.m bouquets can be made, or -1 if there are not enough buds, even when all have bloomed.Input: bloom = [1, 10, 3, 10, 2], m = 3, k = 1
Output: 3With k = 1, a bouquet is one bloomed bud, so the store needs 3 bloomed buds. The earliest day is somewhere between the first bloom, 1, and the last, 10. Search the window [lo, hi), where hi always works, and count the bouquets for each middle day.
| Step | lo | hi | mid | bouquets by day mid | Decision |
|---|---|---|---|---|---|
| 1 | 1 | 10 | 5 | 3 | 3 >= 3, enough, so hi = 5 |
| 2 | 1 | 5 | 3 | 3 | 3 >= 3, so hi = 3 |
| 3 | 1 | 3 | 2 | 2 | 2 < 3, not enough, so lo = 3 |
| end | 3 | 3 | day 3 is the earliest |
By day 3, the buds 0, 2 and 4 have bloomed, so there are 3 bouquets.
Input: bloom = [1, 10, 3, 10, 2], m = 3, k = 2
Output: -1Three bouquets of 2 buds need 6 buds, and there are only 5, so the answer is -1.
Input: bloom = [7, 7, 7, 7, 12, 7, 7], m = 2, k = 3
Output: 12By day 7, the first three buds make one bouquet, but the bud at position 4 blocks the run in the middle. The second bouquet needs the buds 3, 4 and 5, so the answer is day 12.
1 ≤ bloom.length ≤ 100,0001 ≤ bloom[i] ≤ 10,000,000 (days)1 ≤ m, k ≤ 100,000; note that m × k can be up to 10^10Trying every bloom day in order costs about n × n steps, which is 10^10 when every bud has its own day. Each try is a pass over the row. One pass costs n steps, and a binary search over the days up to 10^7 needs about 24 passes, so about 2.4 × 10^6 steps. The product m × k does not fit in 32 bits, so compare it with n using 64-bit numbers.