---
# System prepended metadata

title: LC 2379. Minimum Recolors to Get K Consecutive Black Blocks
tags: [easy, leedcode, Sliding Window, c++]

---

# LC 2379. Minimum Recolors to Get K Consecutive Black Blocks

### [Problem link](https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/)

###### tags: `leedcode` `easy` `c++` `Sliding Window`

You are given a  **0-indexed**  string <code>blocks</code> of length <code>n</code>, where <code>blocks[i]</code> is either <code>'W'</code> or <code>'B'</code>, representing the color of the <code>i<sup>th</sup></code> block. The characters <code>'W'</code> and <code>'B'</code> denote the colors white and black, respectively.

You are also given an integer <code>k</code>, 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 <code>k</code> consecutive black blocks.

**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:** 

- <code>n == blocks.length</code>
- <code>1 <= n <= 100</code>
- <code>blocks[i]</code> is either <code>'W'</code> or <code>'B'</code>.
- <code>1 <= k <= n</code>

## Solution 1
#### C++
```cpp=
class Solution {
public:
    int minimumRecolors(string blocks, int k) {
        int ans = INT_MAX;
        int cnt = 0;
        for (int i = 0; i < blocks.size(); i++) {
            if (blocks[i] == 'W') {
                cnt++;
            }
            if (i < k - 1) {
                continue;
            }
            ans = min(ans, cnt);
            if (blocks[i - k + 1] == 'W') {
                cnt--;
            }
        }
        return ans;
    }
};
```

>### Complexity
>|             | Time Complexity | Space Complexity |
>| ----------- | --------------- | ---------------- |
>| Solution 1  | O(n)            | O(1)             |

## Note
x
