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 ofkconsecutive black blocks.
Input: blocks ="WBBWWBBWBW", k =7Output: 3Explanation:
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 return3.
Example 2:
1
2
3
4
5
Input: blocks ="WBWBBBW", k =2Output: 0Explanation:
No changes need to be made, since 2 consecutive black blocks already exist.Therefore, we return0.
classSolution {
publicintminimumRecolors(String blocks, int k) {
int n = blocks.length();
int wCount = 0; // Count of white blocks in the current windowint ans = Integer.MAX_VALUE;
// Count 'W' in the first window of size kfor (int i = 0; i < k; i++) {
if (blocks.charAt(i) =='W') {
wCount++;
}
}
ans = wCount;
// Slide the window over the stringfor (int i = k; i < n; i++) {
// Add the new block to the windowif (blocks.charAt(i) =='W') {
wCount++;
}
// Remove the first block of the previous windowif (blocks.charAt(i - k) =='W') {
wCount--;
}
// Update the minimum operations ans = Math.min(ans, wCount);
}
return ans;
}
}
classSolution:
defminimumRecolors(self, blocks: str, k: int) -> int:
n = len(blocks)
w_count: int =0# Count of white blocks in the current window ans: int = float('inf')
# Count 'W' in the first window of size kfor i in range(k):
if blocks[i] =='W':
w_count +=1 ans = w_count
# Slide the window over the stringfor i in range(k, n):
# Add the new block to the windowif blocks[i] =='W':
w_count +=1# Remove the first block of the previous windowif blocks[i - k] =='W':
w_count -=1# Update the minimum operations ans = min(ans, w_count)
return ans[LEO](https://leo.ai.pleo.io/chat/leo/a53889f0-556f-4fd9-8742-5b4aaa324b56)