难度:简单。
正确解法:
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int n = nums.size();
if(n == 1)return nums[0];
double average = 0, ans = 0;
for(int i = 0; i < k; i++){
average += nums[i];
}
average /= k;
ans = average;
int left = 1, right = k;
while(right < n){
average -= double(nums[left - 1]) / k;
average += double(nums[right]) / k;
if(ans < average){
ans = average;
}
left++;
right++;
}
return ans;
}
};