# 643. Maximum Average Subarray I

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. 1 <= `k` <= `n` <= 30,000.
2. Elements of the given array will be in the range [-10,000, 10,000].

``````class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int n = nums.size();
vector<int> sums = nums;
for (int i = 1; i < n; ++i) {
sums[i] = sums[i - 1] + nums[i];
}
double mx = sums[k - 1];
for (int i = k; i < n; ++i) {
mx = max(mx, (double)sums[i] - sums[i - k]);
}
return mx / k;
}
};
``````

``````class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double sum = accumulate(nums.begin(), nums.begin() + k, 0), res = sum;
for (int i = k; i < nums.size(); ++i) {
sum += nums[i] - nums[i - k];
res = max(res, sum);
}
return res / k;
}
};
``````

https://discuss.leetcode.com/topic/96134/c-simple-sliding-window-solution

https://discuss.leetcode.com/topic/96154/java-solution-sum-of-sliding-window

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation