AlgoMaster Logo

Maximum Average Subarray I

Last Updated: March 21, 2026

easy
3 min read

Understanding the Problem

We need to find a window of exactly k consecutive elements that gives us the largest possible average. Since the denominator k is fixed for all windows, the subarray with the maximum sum will also have the maximum average. That observation simplifies things: instead of dividing every window's sum by k during comparison, we can just track the maximum sum and divide once at the end.

The question boils down to: what is the most efficient way to compute the sum of every contiguous subarray of length k?

Key Constraints:

  • 1 <= k <= n <= 10^5 → With up to 100,000 elements, an O(n^2) brute force might be tight but an O(n) solution is ideal.
  • -10^4 <= nums[i] <= 10^4 → Elements can be negative, so we cannot skip any window assuming it will be worse.
  • k can equal n → There might be only one valid window (the entire array).

Approach 1: Brute Force

Intuition

The most straightforward way to solve this is to check every possible window of size k. For each starting index i, sum up the k elements from i to i + k - 1, and keep track of the largest sum we find.

This mirrors how you might solve it by hand: slide your finger across the array, stopping at each position to add up the next k numbers, and remember which group had the biggest total.

Algorithm

  1. Initialize maxSum to negative infinity.
  2. For each starting index i from 0 to n - k:
    • Compute the sum of elements from index i to i + k - 1.
    • If this sum exceeds maxSum, update maxSum.
  3. Return maxSum / k as the maximum average.

Example Walkthrough

1i=0: sum(1+12+(-5)+(-6)) = 2, maxSum=2
0
1
i
1
12
2
-5
3
-6
4
50
5
3
1/4

Code

For each window position, we recompute the entire sum from scratch. But consecutive windows overlap in k - 1 elements. What if we reused the previous window's sum and just adjusted for the one element that left and the one that entered?

Approach 2: Sliding Window (Optimal)

Intuition

Here is the key observation: when we move the window one position to the right, we lose the leftmost element and gain a new element on the right. Instead of recalculating the entire sum, we can just subtract the element that dropped off and add the new one that came in.

This is the classic fixed-size sliding window pattern. Compute the sum of the first window once, then "slide" it across the array with a single addition and subtraction per step.

Algorithm

  1. Compute the sum of the first k elements. Call it windowSum.
  2. Set maxSum = windowSum.
  3. For each index i from k to n - 1:
    • Add nums[i] to windowSum (new element entering the window).
    • Subtract nums[i - k] from windowSum (old element leaving the window).
    • Update maxSum if windowSum is larger.
  4. Return maxSum / k.

Example Walkthrough

1Initial window: sum(1+12+(-5)+(-6)) = 2, maxSum=2
0
1
1
12
2
-5
3
-6
4
50
5
3
1/6

Code