Maximum Average Subarray I (LeetCode 643): Solution and Explanation

Easy
Array
Sliding Window

Given an integer array and a length k, find the contiguous block of exactly k numbers with the highest average and return that average.

Intuition

Every candidate block has the same length k. Dividing by the same k never changes which sum is largest, so the problem is really about finding the length-k window with the largest sum. Division happens once, at the very end.

Summing each window from scratch costs k additions per window, which is O(n * k) overall. That is too slow when both n and k are large.

Two neighbouring windows overlap in k - 1 elements. Moving the window one step to the right only changes two things: one element falls off the left edge and one new element joins on the right. So the new sum is the old sum minus the leaving element plus the entering element.

Keep the running window sum and the best sum seen so far. After the window has visited every start position, best / k is the answer.

Approach: Fixed-size sliding window

  1. Add up nums[0..k-1] to get the first window sum, and set best to it.
  2. For each i from k to n - 1, update window += nums[i] - nums[i - k].
  3. After each update, set best = max(best, window).
  4. Return best / k as a floating-point value.

Step-by-step example

nums = [1,12,-5,-6,50,3], k = 4
  1. The first window is [1,12,-5,-6] with sum 2. Set best = 2.
  2. Slide right: 1 leaves and 50 enters. The sum becomes 2 - 1 + 50 = 51, which beats 2, so best = 51.
  3. Slide right: 12 leaves and 3 enters. The sum becomes 51 - 12 + 3 = 42, which does not beat 51.
  4. No more elements remain. The answer is 51 / 4 = 12.75.

Code: Python, Java, C++

1class Solution:
2    def findMaxAverage(self, nums: List[int], k: int) -> float:
3        window = sum(nums[:k])
4        best = window
5        for i in range(k, len(nums)):
6            window += nums[i] - nums[i - k]
7            best = max(best, window)
8        return best / k
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

The first window costs k additions, and each of the remaining n - k slides costs one addition and one subtraction.

Space

O(1)

Only the running sum and the best sum are stored.

Other approaches

Prefix sums (time O(n), space O(n))

Build prefix[i] as the sum of the first i elements, then each window sum is prefix[i + k] - prefix[i]. It is also linear but uses an extra array, which the sliding window avoids.

Brute force (time O(n * k), space O(1))

Sum every window of length k from scratch and keep the maximum. Easy to write, but O(n * k) times out when k is close to n / 2 and n is large.

Common mistakes

  • Starting best at 0. When every number is negative, every window sum is negative and the answer would wrongly be 0. Start from the first window's sum.
  • Doing integer division in Java, C++, C# or Go. Cast to a floating-point type before dividing, or the fraction is lost.
  • Comparing averages instead of sums inside the loop. It works but adds a division per step and invites rounding noise.
  • Off-by-one on the leaving index. When the window ends at i, the element leaving is nums[i - k], not nums[i - k + 1].

Frequently asked questions

Why compare sums instead of averages?

All windows have the same length, so the largest sum always has the largest average. Comparing integer sums is exact and cheaper.

Can the window sum overflow a 32-bit integer?

No. At most 10^5 values of magnitude 10^4 add up to 10^9 in absolute value, which fits in a signed 32-bit integer.

What if k equals n?

There is exactly one window, the whole array. The loop never runs and the answer is the total divided by n.