[LeetCode]643. Maximum Average Subarray I
题目描述
思路
滑窗统计k个数的和,同时保留最大和,结果返回最大和/k
代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double max_sum = 0, cur_sum = 0;
for (int i = 0; i < nums.size(); ++i) {
if (i < k) {
cur_sum += nums[i];
max_sum = cur_sum;
}
else {
cur_sum += nums[i];
cur_sum -= nums[i - k];
max_sum = max(max_sum, cur_sum);
}
}
return max_sum / k;
}
};
int main() {
vector<int> nums = { 1,12,-5,-6,50,3 };
int k = 4;
Solution s;
cout << s.findMaxAverage(nums, k) << endl;
system("pause");
return 0;
}