Maximum Average Subarray I
Easy · Sliding Window · Explanation and code example
Fixed-Length Sliding Sum
How it works
All candidate averages share the same denominator k, so maximizing their sum also maximizes the average. Maintain a running sum of exactly k values, replacing the outgoing value with the incoming one at each step.
Steps
- Sum the first k values and use that as the initial best.
- Slide by adding the new value and subtracting the one leaving.
- Return best sum divided by k.
Complexity
- Time: O(n).
- Space: O(1) after summing the initial window without slicing.
Things to watch for
- Initialize from a real window so all-negative inputs work.
- The window length must remain exactly k.
- Use floating-point division for the final average.
Python code example
class Solution:
def findMaxAverage(self, nums: list[int], k: int) -> float:
summ = sum(nums[i] for i in range(k))
ans = summ
for i in range(k, len(nums)):
summ += nums[i] - nums[i - k]
ans = max(ans, summ)
return ans / k
C++ code example
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double sum = accumulate(nums.begin(), nums.begin() + k, 0);
double ans = sum;
for (int i = k; i < nums.size(); ++i) {
sum += nums[i] - nums[i - k];
ans = max(ans, sum);
}
return ans / k;
}
};
Source and license
Explanation by LC Tracker. Code adapted from walkccc / Peng-Yu Chen · MIT license. Node types are supplied by LeetCode where needed.