AlgoMaster Logo

Maximum Average Subarray I

easyFrequency4 min readUpdated June 23, 2026

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 simplifies the work: instead of dividing every window's sum by k during comparison, 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 does up to 10^10 operations and risks timing out, so an O(n) solution is the target.
  • -10^4 <= nums[i] <= 10^4 → Elements can be negative, so no window can be skipped on the assumption that it will be worse. The maximum possible window sum is 10^5 * 10^4 = 10^9, which fits in a 32-bit signed integer.
  • k can equal n → There may be only one valid window, the entire array.

Approach 1: Brute Force

Intuition

Check every possible window of size k. For each starting index i, sum the k elements from i to i + k - 1, and keep track of the largest sum found. There are n - k + 1 valid starting positions, and each requires summing k elements.

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, the brute force recomputes the entire sum from scratch, even though consecutive windows overlap in k - 1 elements. The next approach reuses the previous window's sum and adjusts only for the one element that left and the one that entered.

Approach 2: Sliding Window (Optimal)

Intuition

When the window moves one position to the right, it loses the leftmost element and gains a new element on the right. Instead of recalculating the entire sum, subtract the element that dropped off and add the one that came in. This is the fixed-size sliding window pattern: compute the sum of the first window once, then move 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