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]
思路:
1,先判断k的长度是不是大于数组长度,大于则求和并处以k
2,以k为一个子序列,从0开始向后移动
注意:数据类型必须为double
#pragma once
#include <iostream>
#include<vector>
#include <algorithm>
#include<numeric>
using namespace std;
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double sum = 0;
double aveg;
int j = k;
//判断k
if (k >= nums.size())
{
double x = (double)accumulate(nums.begin(), nums.end(), 0) / k;
return x;
}
//求第一段k长度的子序列的和及平均
for (int i = 0; i < k; i++)
{
sum += nums[i];
}
aveg = sum / k;
//每次加下一个数进来,减去前一个数,即为当前k长度的子序列的和
for (int i = 0; i < nums.size() && j < nums.size(); i++, j++)
{
sum = sum - nums[i] + nums[j];
if (aveg < sum /k)
{
aveg = double( sum / k);
}
}
return aveg;
}
};