Minimum Recolors To Get K Consecutive Black Blocks
In Minimum Recolors To Get K Consecutive Black Blocks, you receive a string blocks made of 'W' and 'B', plus an integer k. You can recolor white blocks to black, and you need the minimum number of recolors required so at least one contiguous segment of length k becomes fully black.
The key idea is simple: for any window of size k, the number of recolors needed is exactly how many 'W' characters are in that window. So the real task is finding the minimum white count among all length-k windows. A fixed sliding window makes this efficient: initialize the first window, then update counts as one character enters and one leaves.
The judge checks easy and tricky scenarios, including already-black windows requiring zero changes, all-white stretches, and alternating patterns where only one recolor may be needed. Your function should return a single integer minimum, with no extra output, and the answer must be based on contiguous windows only for every tested case.
Examples
Best size-7 window contains 3 white blocks.
Window "BB" already satisfies the requirement.
Need to recolor both blocks in any window.
Algorithm Flow

Best Answers
class Solution {
public int minimum_recolors_to_get_k_consecutive_black_blocks(String blocks, int k) {
int n = blocks.length();
if (k <= 0 || k > n) return 0;
int white = 0;
for (int i = 0; i < k; i++) if (blocks.charAt(i) == 'W') white++;
int best = white;
for (int i = k; i < n; i++) {
if (blocks.charAt(i) == 'W') white++;
if (blocks.charAt(i-k) == 'W') white--;
if (white < best) best = white;
}
return best;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
