1482. Minimum Number of Days to Make m Bouquets #277
-
|
Topics: You are given an integer array You want to make The garden consists of Return the minimum number of days you need to wait to be able to make Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
The problem requires finding the minimum number of days to wait to make exactly Key Points
Approach
Plan
Let's implement this solution in PHP: 1482. Minimum Number of Days to Make m Bouquets <?php
/**
* @param Integer[] $bloomDay
* @param Integer $m
* @param Integer $k
* @return Integer
*/
function minDays($bloomDay, $m, $k) {
if (($m * $k) > count($bloomDay)) {
return -1;
}
$start = 0;
$end = max($bloomDay);
$minDays = -1;
while ($start <= $end) {
$mid = ceil(($start + $end) / 2);
if (canMakeBouquets($bloomDay, $mid, $k) >= $m) {
$minDays = $mid;
$end = $mid - 1;
} else {
$start = $mid + 1;
}
}
return $minDays;
}
/**
* @param Integer[] $bloomDay
* @param Float $mid
* @param Integer $k
* @return Integer
*/
function canMakeBouquets($bloomDay, $mid, $k) {
$bouquetsMade = 0;
$flowersCollected = 0;
foreach ($bloomDay as $day) {
// If the flower is bloomed, add to the set. Else reset the count.
if ($day <= $mid) {
$flowersCollected += 1;
} else {
$flowersCollected = 0;
}
if ($flowersCollected == $k) {
$bouquetsMade += 1;
$flowersCollected = 0;
}
}
return $bouquetsMade ;
}
// Example usage:
$bloomDay = [1,10,3,10,2];
$mid = 3;
$k = 1;
echo minDays($bloomDay, $mid, $k) . "\n"; // Output: 3
$bloomDay = [1,10,3,10,2];
$mid = 3;
$k = 2;
echo minDays($bloomDay, $mid, $k) . "\n"; // Output: -1
$bloomDay = [7,7,7,7,12,7,7];
$mid = 2;
$k = 3;
echo minDays($bloomDay, $mid, $k) . "\n"; // Output: 12
?>Explanation:Helper Function:
|
Beta Was this translation helpful? Give feedback.
The problem requires finding the minimum number of days to wait to make exactly
mbouquets, each containingkadjacent flowers, using the arraybloomDay. If it is not possible, return-1. The task is efficiently solved using a binary search approach on the number of days.Key Points
mbouquets inxdays, it will also be possible for all days greater thanx.kadjacent flowers. This introduces the need for sequential checks.m * k > n, it is impossible to make the bouquets, and the function should immediately return-1.App…