[LeetCode] Minimum Recolors to Get K Consecutive Black Blocks

2379. Minimum Recolors to Get K Consecutive Black Blocks

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int minimumRecolors(string blocks, int k) {
int res = INT_MAX, l = 0, r = 0, n = blocks.length(), now = 0;
for(int i = 0; i < blocks.size(); i++) {
if(blocks[i] == 'B') now++;
if(i >= k and blocks[i-k] == 'B') now--;
if(i + 1 >= k) res = min(res, k - now);
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/20/PS/LeetCode/minimum-recolors-to-get-k-consecutive-black-blocks/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.