Search for a command to run...
Initialization
On a given day, every flower whose bloom day has passed is open. Bouquets need 3 adjacent open flowers, so only unbroken runs count. Waiting longer can only open more flowers, so the bouquet count never decreases — that monotonicity is what makes the day searchable.
Binary Search on the Answer
1function possible(nums, day, m, k) {2 const n = nums.length;3 let cnt = 0; // run of bloomed flowers4 let noOfB = 0; // bouquets formed5 6 for (let i = 0; i < n; i++) {7 if (nums[i] <= day) {8 cnt++;9 } else {10 // Run broken — bank whole bouquets and reset11 noOfB += Math.floor(cnt / k);12 cnt = 0;13 }14 }15 noOfB += Math.floor(cnt / k);//low: 7high: 1316 17 return noOfB >= m;18}19 20function roseGarden(n, nums, k, m) {21 // Not enough flowers to ever make m bouquets22 if (m * k > n) return -1;23 24 let mini = Infinity, maxi = -Infinity;25 for (let i = 0; i < n; i++) {26 mini = Math.min(mini, nums[i]);27 maxi = Math.max(maxi, nums[i]);28 }29 30 let left = mini, right = maxi, ans = -1;31 while (left <= right) {32 const mid = left + Math.floor((right - left) / 2);33 34 if (possible(nums, mid, m, k)) {35 ans = mid;36 right = mid - 1; // try an earlier day37 } else {38 left = mid + 1;39 }40 }41 return ans;42}