BudiBadu Logo

Minimum Recolors To Get K Consecutive Black Blocks

Sliding Window Easy 0 views
Like0

You are given a string blocks made of characters 'W' (white) and 'B' (black), and an integer k. You may recolor any white block to black. Return the minimum number of recolors needed so that at least one substring of length k becomes all black.

Think of each window of length k: the number of recolors needed for that window is exactly the number of white blocks inside it. So the task becomes finding the minimum white count over all windows of size k.

Use a fixed-size sliding window to maintain white count in O(n): add incoming character, remove outgoing character, and keep the minimum.

Example 1:

Input: blocks = "WBBWWBBWBW", k = 7

Output: 3

Explanation: The best window of length 7 has 3 white blocks, so recolor 3.

Example 2:

Input: blocks = "WBWBBBW", k = 2

Output: 0

Explanation: Window "BB" already has all black blocks.

Example 3:

Input: blocks = "WWWW", k = 2

Output: 2

Explanation: Every length-2 window has two white blocks.

Constraints: 1 <= blocks.length <= 10^5, 1 <= k <= blocks.length

Algorithm Flow

Recommendation Algorithm Flow for Minimum Recolors To Get K Consecutive Black Blocks - Budibadu
Recommendation Algorithm Flow for Minimum Recolors To Get K Consecutive Black Blocks - Budibadu

Best Answers

java
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;
    }
}