LeetCode 2379: Minimum Recolors to Get K Consecutive Black Blocks

Problem Description

Explanation

To solve this problem, we can use a sliding window approach. We will maintain a window of size k and slide it through the array to find the minimum number of recolor operations needed to get k consecutive black blocks. We will count the number of white blocks inside the window and keep track of the minimum count needed to achieve k consecutive black blocks.

Algorithm

  1. Initialize variables: minOps to store the minimum operations needed, count to count white blocks in the window, and minCount to store the minimum count needed for k consecutive black blocks.
  2. Iterate through the blocks array from 0 to n-k.
  3. For each window of size k, count the number of white blocks inside the window.
  4. Update minCount with the minimum of current minCount and (k - count) (operations needed to convert white blocks to black blocks).
  5. Update minOps with the minimum of current minOps and minCount.
  6. Return minOps as the result.

Time Complexity

The time complexity of this algorithm is O(n), where n is the length of the input string blocks.

Space Complexity

The space complexity is O(1) as we are using constant extra space.

Solutions

class Solution {
    public int minRecolors(String blocks, int k) {
        int n = blocks.length();
        int minOps = Integer.MAX_VALUE;
        
        for (int i = 0; i <= n - k; i++) {
            int count = 0;
            for (int j = i; j < i + k; j++) {
                if (blocks.charAt(j) == 'W') {
                    count++;
                }
            }
            int minCount = Math.min(minOps, k - count);
            minOps = Math.min(minOps, minCount);
        }
        
        return minOps == Integer.MAX_VALUE ? 0 : minOps;
    }
}

Loading editor...