Maximum Average Subarray I
Find the contiguous subarray of fixed length k with the highest average using a sliding window running sum.
01The problem
You are given an integer array nums and an integer k. Find a contiguous subarray of length k that has the maximum average value, and return this value. Any answer with a calculation error less than 10⁻⁵ will be accepted.
| Input | Output | Why |
|---|---|---|
nums = [1, 12, -5, -6, 50, 3], k = 4 | 12.75 | Window [12, -5, -6, 50] has sum 51, 51 / 4 = 12.75 |
nums = [5], k = 1 | 5.0 | Single element window is 5.0 |
nums = [-1, -2, -3], k = 2 | -1.5 | Window [-1, -2] has sum -3, -3 / 2 = -1.5 |
Constraints: 1 ≤ k ≤ n ≤ 100,000, -10,000 ≤ nums[i] ≤ 10,000.
02How to spot it
- A contiguous subarray of fixed length k is requested.
- Finding the largest average across all windows of identical length
kis equivalent to finding the maximum sum. - Neighboring windows share
k - 1elements, so each step can update the sum in O(1) by adding the incoming element and subtracting the outgoing element.
So: fixed-size sliding window.
03Pseudocode
sum = a[0] + ... + a[k-1]
best = sum
for i from k to n - 1:
sum += a[i] - a[i - k]
best = max(best, sum)
return best / k- Compute the sum of the first
kelements. - Slide the window one element right: add the new arrival, drop the one that fell off the left.
- Track the maximum sum seen, and divide by
konce at the end.
04Watch it work
Compute the sum of the first 4 elements: 1 + 12 - 5 - 6 = 2.
Pseudocode
- sum = a[0] + ... + a[k-1]
- best = sum
- for i from k to n - 1:
- sum += a[i] - a[i - k]
- best = max(best, sum)
- return best / k
Variables
- sum
- 2
- k
- 4
05Step-by-step dry run
- 110121-52-6350435LR
Compute the sum of the first 4 elements: 1 + 12 - 5 - 6 = 2.
sum = 2k = 4
- 210121-52-6350435LR
Initialize best = 2 with the first window sum.
sum = 2best = 2
- 310121-52-6350435LR
Slide window right: add 50 (entering at index 4), drop 1 (leaving at index 0). New sum: 51.
i = 4sum = 51best = 51
- 410121-52-6350435LR
Sum 51 beats previous best! Update best = 51. Window: [12, -5, -6, 50].
sum = 51best = 51
- 510121-52-6350435LR
Slide window right: add 3 (entering at index 5), drop 12 (leaving at index 1). New sum: 42.
i = 5sum = 42best = 51
- 610121-52-6350435LR
Sum 42 does not beat best 51. Best remains 51.
sum = 42best = 51
- 710121-52-6350435
Maximum window sum is 51. Divide by k (4) to get the maximum average: 12.75.
best = 51k = 4result = 12.75
06Java solution
public class MaxAverageSubarray {
public static double findMaxAverage(int[] nums, int k) {
int sum = 0;
for (int i = 0; i < k; i++) sum += nums[i]; // first window
int best = sum;
for (int i = k; i < nums.length; i++) {
sum += nums[i] - nums[i - k]; // slide: add new, drop old
best = Math.max(best, sum);
}
return (double) best / k;
}
public static void main(String[] args) {
System.out.println(findMaxAverage(new int[]{1, 12, -5, -6, 50, 3}, 4));
System.out.println(findMaxAverage(new int[]{5}, 1));
System.out.println(findMaxAverage(new int[]{-1, -2, -3}, 2));
}
}12.75 5.0 -1.5
Tricky lines, decoded
sum += nums[i] - nums[i - k]: Slides the window in O(1) arithmetic without summingkelements again.(double) best / k: Cast todoublebefore dividing, otherwise Java performs integer division and truncates decimal values.
07Why it works
Consecutive windows of length k overlap everywhere except at their boundaries: exactly one element leaves the left, and one enters the right. Adding the newcomer and subtracting the departed number produces the exact total of the new window in O(1). Because all windows have length k, maximizing the sum directly maximizes the average.
Invariant: Before checking the window ending at index i, sum equals the exact sum of nums[i - k + 1 .. i].
08Time and space
- Time: O(n). A single pass computes the initial window and slides across the remaining
n - kpositions. - Space: O(1). Only two scalar variables (
sumandbest) are tracked.
09Edge cases
| Input | Output | Why it matters |
|---|---|---|
[5], k = 1 | 5.0 | Single element array (k = n = 1) |
[-1, -2, -3], k = 2 | -1.5 | All-negative values |
[0, 4, 0, 3, 2], k = 1 | 4.0 | k = 1 is just the maximum element |
[7, 7, 7, 7], k = 4 | 7.0 | Entire array is the only window (k = n) |
[-10000, 10000], k = 1 | 10000.0 | Large negative and positive values |
10Common mistakes
- Integer division. Writing
best / kreturns12.0instead of12.75. Always cast(double) best / k. - Initializing
best = 0. An all-negative array (like[-5], k = 1) would wrongly return0.0. Initializebest = sumfrom the first window. - Dividing on every iteration. Calculating
sum / (double) kinside the loop causes unnecessary floating-point division and precision drift. Compare integer sums and divide once at the end.
11Other approaches
| Approach | Time | Space | Use when |
|---|---|---|---|
| Re-sum each window | O(n · k) | O(1) | Only acceptable when k = 1 or tiny |
| Sliding sum | O(n) | O(1) | Default interview solution |
| Prefix sums | O(n) | O(n) | Multiple static range queries |
12In the interview
- Streaming data? Maintain a queue of the last
kvalues and a running sum. When an element arrives, enqueue it and dequeue the front element. - Why compare sums instead of averages? Because
kis identical for every candidate, a larger sum always gives a larger average. Integer math avoids rounding mistakes.
13Check your understanding
Quiz · 2 questions
0 of 2 answered
1. Why do we initialize best with the sum of the first window instead of 0?
2. Why is it better to compare sums inside the loop and divide by k only at the end?
14Solve it yourself
Try it on LeetCode #643.