文章目录
- 题目描述
- 题解思路
- 题解代码
- 题目链接
题目描述
题解思路
本题可以转换为求长度为k的子数组中白色块的最少数量
我们遍历长度为k的窗口,我们只需要记录窗口内的白色块的数量即可,遍历过程中刷新白色块的数量的最小值
题解代码
impl Solution {
pub fn minimum_recolors(blocks: String, k: i32) -> i32 {
let blocks = blocks.as_bytes();
let mut sum = 0;
for i in 0..k as usize {
if blocks[i] == b'W' {
sum += 1;
}
}
let mut min_sum = sum;
for i in k as usize..blocks.len() {
if blocks[i] == b'W' {
sum += 1;
}
if blocks[i-k as usize] == b'W' {
sum -= 1;
}
min_sum = min_sum.min(sum);
}
min_sum
}
}
题目链接
https://leetcode.cn/problems/minimum-recolors-to-get-k-consecutive-black-blocks/