You are given a 0-indexed string blocks
of length n
, where blocks[i]
is either 'W'
or 'B'
, representing the color of the ith
block. The characters 'W'
and 'B'
denote the colors white and black, respectively.
You are also given an integer k
, which is the desired number of consecutive black blocks.
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 k
consecutive black blocks.
Example 1:
Input: blocks = "WBBWWBBWBW", k = 7 Output: 3 Explanation: One way to achieve 7 consecutive black blocks is to recolor the 0th, 3rd, and 4th blocks so that blocks = "BBBBBBBWBW". It can be shown that there is no way to achieve 7 consecutive black blocks in less than 3 operations. Therefore, we return 3.
Example 2:
Input: blocks = "WBWBBBW", k = 2 Output: 0 Explanation: No changes need to be made, since 2 consecutive black blocks already exist. Therefore, we return 0.
Constraints:
n == blocks.length
1 <= n <= 100
blocks[i]
is either'W'
or'B'
.1 <= k <= n
class Solution:
def minimumRecolors(self, blocks: str, k: int) -> int:
cnt = blocks[:k].count('W')
ans = cnt
i, n = k, len(blocks)
while i < n:
cnt += blocks[i] == 'W'
cnt -= blocks[i-k] == 'W'
ans = min(ans, cnt)
i += 1
return ans
class Solution {
public int minimumRecolors(String blocks, int k) {
int cnt = 0, n = blocks.length();
int i = 0;
for (; i < k; ++i) {
if (blocks.charAt(i) == 'W') {
++cnt;
}
}
int ans = cnt;
for (; i < n; ++i) {
cnt += blocks.charAt(i) == 'W' ? 1 : 0;
cnt -= blocks.charAt(i - k) == 'W' ? 1 : 0;
ans = Math.min(ans, cnt);
}
return ans;
}
}
class Solution {
public:
int minimumRecolors(string blocks, int k) {
int cnt = 0, n = blocks.size();
int i = 0;
for (; i < k; ++i) cnt += blocks[i] == 'W';
int ans = cnt;
for (; i < n; ++i) {
cnt += blocks[i] == 'W';
cnt -= blocks[i - k] == 'W';
ans = min(ans, cnt);
}
return ans;
}
};
func minimumRecolors(blocks string, k int) int {
cnt, n := 0, len(blocks)
i := 0
for ; i < k; i++ {
if blocks[i] == 'W' {
cnt++
}
}
ans := cnt
for ; i < n; i++ {
if blocks[i] == 'W' {
cnt++
}
if blocks[i-k] == 'W' {
cnt--
}
ans = min(ans, cnt)
}
return ans
}
func min(a, b int) int {
if a < b {
return a
}
return b
}