---
# System prepended metadata

title: LeetCode 2379. Minimum Recolors to Get K Consecutive Black Blocks
tags: [Leetcode]

---

# LeetCode 2379. Minimum Recolors to Get K Consecutive Black Blocks
[LeetCode 2379. Minimum Recolors to Get K Consecutive Black Blocks](https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/) (<font color=#00AF9B>Easy</font> 59.1%) 

<!-- 
(<font color=#00AF9B>Easy</font> 59.1%) 
(<font color=#FFB800>Medium</font> 39.6%)
(<font color=#FF375F>Hard</font>)
 -->

- 限制 :

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

- Solution
    這題參考自[這裡](https://hackmd.io/@Inversionpeter/rkuNcYAR5)、[這裡](https://home.gamer.com.tw/artwork.php?sn=5752256)，主要方法就是以他的大小去看在這個區塊底下有多少個 white block ，利用 sliding window 沿路找到最少 white block。
    - 時間複雜度: $O(n)$
    - 空間複雜度: $O(1)$

- 程式碼
    ```c++=
    class Solution {
    public:
        int minimumRecolors(string blocks, int k) {
            int white_count = 0;
            for (int i = 0; i < k; i++) {
                if (blocks[i] == 'W')
                    white_count += 1;
            }
            int minimun = white_count;
            for (int i = k; i < blocks.size(); i++) {
                if (blocks[i] == 'W')
                    white_count++;
                if (blocks[i - k] == 'W')
                    white_count--;
                minimun = min(minimun, white_count);
            }
            return minimun;
        }
    };
    ```
