The Maximum Average Subarray I problem provides an integer array and an integer k. Your task is to find a contiguous subarray of exactly length k that has the maximum average value, and return this maximum average. Because the length k is fixed, maximizing the average is mathematically identical to maximizing the sum of the subarray.
This is the textbook introduction to the Fixed-Size Sliding Window pattern. Interviewers use it as an early screening question to verify that a candidate knows how to avoid nested loops. It evaluates whether you can maintain a running sum dynamically by adding the incoming element and subtracting the outgoing element.
This problem relies entirely on the Fixed-Size Sliding Window pattern.
k elements). This is your initial current_sum and max_sum.arr[i]), and subtract the old element leaving the window on the left (arr[i - k]).max_sum = Math.max(max_sum, current_sum).(double) max_sum / k.Array: [1, 12, -5, -6, 50, 3], k = 4.
[1, 12, -5, -6]. Sum = 2. max_sum = 2.50, remove 1.
curr_sum = 2 + 50 - 1 = 51.
max_sum = 51.3, remove 12.
curr_sum = 51 + 3 - 12 = 42.
max_sum = 51.
End of array. The maximum sum is 51. The maximum average is .A frequent mistake is calculating the average inside the loop and using max_avg = Math.max(max_avg, current_avg). While this works, performing floating-point division on every single iteration is computationally expensive and introduces unnecessary precision risks. It is far more optimal to simply track the maximum integer sum during the loop, and only perform the division by k exactly once at the very end.
When solving fixed-window problems, the standard format is to build the initial window in a dedicated for loop from 0 to k-1. Then, create a second for loop starting from k to n-1 that does the sliding (add i, subtract i-k). This separation of "build" and "slide" logic makes the code highly readable and drastically reduces off-by-one index errors.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Defuse the Bomb | Easy | Solve | |
| Alternating Groups I | Easy | Solve | |
| Diet Plan Performance | Easy | Solve | |
| Longest Even Odd Subarray With Threshold | Easy | Solve | |
| Count Subarrays Where Max Element Appears at Least K Times | Medium | Solve |