DDSA Solutions

2379. Minimum Recolors to Get K Consecutive Black Blocks

Time: O(n)
Space: O(1)
Advertisement

Intuition

Count black cells after painting rows and columns. Inclusion-exclusion: |rows| * m + |cols| * n - |rows| * |cols|.

Algorithm

  1. 1Count unique rows and unique cols from coordinates.
  2. 2Answer = uniqueRows * n + uniqueCols * m - uniqueRows * uniqueCols.

Common Pitfalls

  • Intersection cells (row and col both painted) are counted twice without subtraction.
2379.cs
C#
// Approach: Sliding window of size k; count max 'B's in any window; answer = k - maxB.
// Time: O(n) Space: O(1)

public class Solution
{
    public int MinimumRecolors(string blocks, int k)
    {
        int countB = 0;
        int maxCountB = 0;

        for (int i = 0; i < blocks.Length; ++i)
        {
            if (blocks[i] == 'B')
                ++countB;
            if (i >= k && blocks[i - k] == 'B')
                --countB;
            maxCountB = Math.Max(maxCountB, countB);
        }

        return k - maxCountB;
    }
}
Advertisement
Was this solution helpful?