题目
643. Maximum Average Subarray I
解题思路
遍历找出连续k个和最大的数字,最后返回和/k即可。这道题目思路简单。
具体代码
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double maxsum = 0;
for (int i = 0; i < k; i++)
maxsum += nums[i];
int sum = maxsum;
for (int i = 1; i < nums.size() - k + 1; i++) {
sum += nums[i+k-1] - nums[i-1];
maxsum = sum > maxsum ? sum : maxsum;
}
return maxsum / k;
}
};