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.
Minimum Recolors to Get K Consecutive Black Blocks LeetCode Contest
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.length1 <= n <= 100blocks[i]is either'W'or'B'.1 <= k <= n
Solution
- Sliding window of size K and minimize the no. of ‘W’ in the window
- When founding a ‘W’ in forwarding pointer, increment counter
- when found ‘W’ in the back pointer, decrement counter
- Take the minimum of the counter as the answer
int minimumRecolors(string blocks, int k) {
int back = 0, front = 0, count_w = 0, ans = INT_MAX;
while(front < blocks.size()){
if(blocks[front] == 'W'){ count_w++; }
if(front - back + 1 == k){
ans = min(ans, count_w);
if(blocks[back] == 'W') count_w--;
back++;
}
front++;
}
return ans;
} public int minimumRecolors(String blocks, int k) {
int min = Integer.MAX_VALUE;
for (int lo = -1, hi = 0, white = 0; hi < blocks.length(); ++hi) {
white += blocks.charAt(hi) == 'W' ? 1 : 0;
if (hi - lo >= k) { // the window reaches size of k.
min = Math.min(min, white); // update minimum.
// slide 1 step right the lower bound of the sliding
// window and update the value of white count.
white -= blocks.charAt(++lo) == 'W' ? 1 : 0;
}
}
return min;
} def minimumRecolors(self, blocks: str, k: int) -> int:
lo, white, mi = -1, 0, inf
for hi, c in enumerate(blocks):
if c == 'W':
white += 1
if hi - lo >= k:
mi = min(white, mi)
lo += 1
white -= blocks[lo] == 'W'
return miHappy Learning – If you require any further information, feel free to contact me.
![[Solved] Minimum Recolors to Get K Consecutive Black Blocks LeetCode Contest [Solved] Minimum Recolors to Get K Consecutive Black Blocks LeetCode Contest](https://realcoder.techss24.com/wp-content/uploads/2022/08/Solved-Minimum-Recolors-to-Get-K-Consecutive-Black-Blocks-LeetCode-Contest.png)
![[Solved] Maximum XOR After Operations LeetCode Contest Problem](https://realcoder.techss24.com/wp-content/uploads/2022/06/Solved-Maximum-XOR-After-Operations-LeetCode-Contest-Problem-300x200.png)

