Leetcode 2379. Minimum Recolors to Get K Consecutive Black Blocks
You are given a string blocks representing a row of blocks where each block can be either ‘W’ (white) or ‘B’ (black). You are also given an integer k, the number of consecutive blocks you need to get. You need to find the minimum number of recolors needed to get at least k consecutive black blocks.
blocks = "WBBWWBBWBW", k = 73k to iterate through the string.k.k.k is the answer, as these are the blocks that need to be recolored.O(n) time, where n is the length of the blocks string.Here’s the C++ implementation of the solution:
#include <string>
#include <algorithm>
class Solution {
public:
int minimumRecolors(std::string blocks, int k) {
int n = blocks.size();
// Initial count of 'W' in the first window of size k
int whiteCount = 0;
for (int i = 0; i < k; ++i) {
if (blocks[i] == 'W') {
++whiteCount;
}
}
int minRecolors = whiteCount;
// Sliding window approach
for (int i = k; i < n; ++i) {
// Remove the effect of the leftmost block of the previous window
if (blocks[i - k] == 'W') {
--whiteCount;
}
// Add the effect of the current block
if (blocks[i] == 'W') {
++whiteCount;
}
// Update minimum recolors needed
minRecolors = std::min(minRecolors, whiteCount);
}
return minRecolors;
}
};
By following this approach, you can efficiently find the minimum number of blocks that need to be recolored to get at least k consecutive black blocks.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?