问题描述:
You are given an integer array nums consisting of n elements, and an integer k.
Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value.
限定条件:
n == nums.length
1 <= k <= n <= 100000
-10000 <= nums[i] <= 10000
求连续k个数据平均值的最大值(即最大滑动平均值)
这道题第一遍刷错了三次,应当引起极高重视
思路:
首先注意的一点是Double.MIN_VALUE不是负数,它是一个极小的正数
滑动窗口经典题目
先求出原始窗口的值,即从0到k-1的值,这个值作为窗口的原始值。
然后窗口右边框加一,同时窗口左边框加一,等到新窗口值,把这个新窗口值与之前的最大记录比较。
代码如下:
class Solution {
public double findMaxAverage(int[] nums, int k) {
double sum = 0;
//initialize the avaerage with the first sliding window
for (int i=0; i<k; i++){
sum = sum + nums[i];
}
double res = sum;
for (int i=k; i<nums.length; i++){
sum = sum + nums[i]-nums[i-k];
res=Math.max(res,sum);
}
return res/k;
}
}
时间复杂度:O(n)