DSA AnimatorDSA animations
Maximum Average Subarray I LC #643 Easy Sliding Window
Approach
Fixed Sliding Window
Build first window of size k, then slide: add incoming element, subtract outgoing. Track max sum. O(n) time.
Sum: 0
Window Sum
sum: 0 avg: 0 best: —
k
—
Window [L..R]
—
Sum
—
Max Avg
—
Press Play to start
📊
—
Maximum Average
— —
—
Algorithm
1
Build first window: sum of nums[0..k-1]
2
Slide: sum += nums[r] - nums[r-k]
3
maxSum = max(maxSum, sum)
4
Return maxSum / k
Time
O(n)
Space
O(1)
Why It Works

Fixed window — instead of re-summing from scratch each time, slide: add incoming element, subtract outgoing.

This reduces the naïve O(nk) approach to O(n).

Max sum ÷ k = max avg (dividing by a constant k preserves order).

How to solve Maximum Average Subarray I

LeetCode 643 · Easy · Arrays · Pattern: Fixed Sliding Window

Why the obvious approach is slow

Summing every window from scratch costs O(n) times k. Neighbouring windows share almost all their numbers, so that work is repeated.

The key idea

Since every window has the same length, the largest average is just the largest sum. Compute the first window once. Then slide: add the number entering on the right, and subtract the one leaving on the left.

Remember

A fixed window slides by adding the new number and removing the oldest. Same length means the largest average is the largest sum.

Run the animation above on your own input, or watch the 1:31 video explanation of Maximum Average Subarray I with a dry run and Java code.

More Arrays problems