Difficulty: Easy
Topics: Strings, Sliding Window
Hint: Use a sliding window to count the number of white blocks in every subarray of length k
and find the minimum number to recolor.
You are given a 0-indexed string blocks
of length n
, where blocks[i]
is either 'W'
or 'B'
, representing the color of the i
th 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.
blocks = "W"
, k = 1
1
blocks = "B"
, k = 1
0
blocks = "WWWW"
, k = 2
2
blocks = "BWBWBW"
, k = 3
1
"BWB"
contains 2 black blocks. Recoloring the white block in this window yields 3 consecutive black blocks.n == blocks.length
1 <= n <= 100
blocks[i]
is either 'W'
or 'B'
.1 <= k <= n
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/description/
Loading component...
Loading component...
Main Function is not defined.
INPUT : blocks = "WBBWWBBWBW"
Output: 3
public static int minimumRecolors(String blocks, int k) {
int bCount = 0;
int ans = Integer.MAX_VALUE;
for (int i = 0; i < blocks.length(); i++) {
if (i - k >= 0 && blocks.charAt(i - k) == 'B'){
bCount--;
}//If End
if (blocks.charAt(i) == 'B') {
bCount++;
}//If End
ans = Math.min(ans, k - bCount);
}//Loop End
return ans;
}//function end
Utility Function is not required.