Sliding Window Technique - Part 5

Standard sliding window technique here, my implementation was a little more convoluted this time around (I'm sure there is a clearer way to detect the window) but did the work. Notice that the constraints are very generous, hence even an N^2 solution (2-nested loops) would be able to solve this problem (the sliding window solves it in linear time). Code is down below, cheers, ACC.

Minimum Recolors to Get K Consecutive Black Blocks - LeetCode

2379. Minimum Recolors to Get K Consecutive Black Blocks
Easy

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.

 

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:

  • n == blocks.length
  • 1 <= n <= 100
  • blocks[i] is either 'W' or 'B'.
  • 1 <= k <= n

public class Solution {
    public int MinimumRecolors(string blocks, int k)
    {
        int retVal = Int32.MaxValue;
        int currentWindowRecolors = 0;

        int left = 0;
        int right = -1;
        for (; ; )
        {
            right++;
            if (right >= blocks.Length) break;
            if (right - left + 1 > k)
            {
                if (blocks[left] == 'W') currentWindowRecolors--;
                left++;
            }
            if (blocks[right] == 'W') currentWindowRecolors++;
            if(right >= k - 1) retVal = Math.Min(retVal, currentWindowRecolors);
        }

        return retVal;
    }
}

 

Comments

Popular posts from this blog

Changing the root of a binary tree

ProjectEuler Problem 719 (some hints, but no spoilers)

The Power Sum, a recursive problem by HackerRank