Title
Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.
Example 1:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Note: 1 <= k <= n <= 30,000. Elements of the given array will be in the range [-10,000, 10,000].
题目大意:找连续k个数字,平均数最大
Solution
用的滑动窗口方法,其实也可以用累积和的,就是sum[i]表示的是从num[0]-num[i],因此,sum[i]-sum[i-k]就是这k个数字,可能不太准,是思想
//cpp:
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
if (nums.size() >= k) {
double t = 0;
for (int i = 0; i < k; i++) {
t += nums[i];
}
double mans = t;
for (int i = k; i < nums.size(); i++) {
t = t + nums[i] - nums[i - k];
if (t> mans) {
mans = t;
}
}
return mans / k;
}
}
};