Maximum Average Subarray I

Maximum average of any length-k subarray — fixed-size sliding window over a running sum.

Easy
Time O(n) Space O(1)
LeetCode
3 min read
sliding-window array

Problem#

Find the contiguous subarray of length k with the maximum average. Return that average.

Examples#

  • nums = [1,12,-5,-6,50,3], k = 412.75

Constraints#

  • 1 <= k <= nums.length <= 10^5.

Approach#

Fixed-size window. Maintain a running sum; at each step add the new element and subtract the leaving one. Track the max sum, divide by k at the end.

Solution#

Maximum Average Subarray I
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
long long sum = 0;
for (int i = 0; i < k; ++i) sum += nums[i];
long long best = sum;
for (int i = k; i < (int)nums.size(); ++i) {
sum += nums[i] - nums[i - k];
best = max(best, sum);
}
return (double)best / k;
}
};

Editorial#

The fixed-window pattern: precompute first window, then “rolling” updates. Using long long avoids overflow (nums[i] up to 10⁴ × 10⁵ = 10⁹, still fits, but defensive). Dividing once at the end keeps the comparison integer and exact.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.