2379. Minimum Recolors to Get K Consecutive Black Blocks #1405
-
Topics: You are given a 0-indexed string You are also given an integer In one operation, you can recolor a white block such that it becomes a black block. Return the minimum number of operations needed such that there is at least one occurrence of Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the minimum number of operations required to convert a substring of length Approach
Let's implement this solution in PHP: 2379. Minimum Recolors to Get K Consecutive Black Blocks <?php
/**
* @param String $blocks
* @param Integer $k
* @return Integer
*/
function minimumRecolors($blocks, $k) {
$n = strlen($blocks);
$min_ops = $k; // Initialize with maximum possible value (all W's)
for ($i = 0; $i <= $n - $k; $i++) {
$current = substr($blocks, $i, $k);
$count = substr_count($current, 'W');
if ($count < $min_ops) {
$min_ops = $count;
}
}
return $min_ops;
}
// Example usage:
//Example 1
$blocks = "WBBWWBBWBW", $k = 7;
echo minimumRecolors($blocks, $k); // Output: 3
//Example 2
$blocks = "WBWBBBW", $k = 2;
echo minimumRecolors($blocks, $k); // Output: 0
?> Explanation:
This approach efficiently checks all possible substrings of length |
Beta Was this translation helpful? Give feedback.
We need to determine the minimum number of operations required to convert a substring of length
k
in the given stringblocks
into consecutive black blocks ('B'). Each operation involves changing a white block ('W') to a black block.Approach
k
to traverse the stringblocks
. This allows us to efficiently check each possible substring of lengthk
.Let's implement this solution in PHP: 2379. Minimum Recolors to Get K Consecuti…