Skip to content

2379. Minimum Recolors to Get K Consecutive Black Blocks 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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 = max(maxCountB, countB);
    }

    return k - maxCountB;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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.charAt(i) == 'B')
        ++countB;
      if (i >= k && blocks.charAt(i - k) == 'B')
        --countB;
      maxCountB = Math.max(maxCountB, countB);
    }

    return k - maxCountB;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def minimumRecolors(self, blocks: str, k: int) -> int:
    countB = 0
    maxCountB = 0

    for i, block in enumerate(blocks):
      if block == 'B':
        countB += 1
      if i >= k and blocks[i - k] == 'B':
        countB -= 1
      maxCountB = max(maxCountB, countB)

    return k - maxCountB