题目描述
题解思路
我们遍历长度为k的窗口,我们只需要记录窗口内的最大和即可,遍历过程中刷新最大值
结果为窗口长度为k的最大和 除以 k
题解代码
impl Solution {
pub fn find_max_average(nums: Vec<i32>, k: i32) -> f64 {
let mut sum = 0;
// 填满长度为k的窗口
for i in 0..k as usize {
sum += nums[i];
}
let mut max_sum = sum;
// 移动窗口,并记录最大的窗口和
for i in k as usize..nums.len() {
sum += nums[i] - nums[i - k as usize];
max_sum = max_sum.max(sum);
}
max_sum as f64 / k as f64
}
}
题目链接
https://leetcode.cn/problems/maximum-average-subarray-i/description/