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
- Initialize variables:
minOps
to store the minimum operations needed,count
to count white blocks in the window, andminCount
to store the minimum count needed for k consecutive black blocks. - Iterate through the blocks array from 0 to n-k.
- For each window of size k, count the number of white blocks inside the window.
- Update
minCount
with the minimum of currentminCount
and(k - count)
(operations needed to convert white blocks to black blocks). - Update
minOps
with the minimum of currentminOps
andminCount
. - 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...