Maximum Average Subarray I
Maximum Average Subarray I is LeetCode 643 (Easy). You get an integer array nums and an integer k. Return the largest average of any contiguous run of exactly k numbers.
- The numbers can be negative.
- An answer within
10⁻⁵of the true value is accepted.
The array can hold 10⁵ numbers and k can be close to that, so adding up every window from scratch (about n × k additions) is too slow.
- n == nums.length
- 1 <= k <= n <= 10⁵
- -10⁴ <= nums[i] <= 10⁴
Intuition
Every window holds exactly k numbers, so the window with the largest sum also has the largest average. Dividing by the same positive k never changes which of two sums is bigger. So the problem is really: find the largest sum of k neighbours, then divide once.
Two windows next to each other share k − 1 numbers. Moving the window one place right drops one number on the left and adds one on the right, so the new sum is the old sum minus the number that left plus the number that arrived. Each move costs two operations instead of k.
A fixed window length and a question about the best sum, average or count inside it points to a sliding window that updates one number in and one number out.
Approach
Before reading on, write the sum of window i + 1 using only the sum of window i and two array values. Then decide what the best sum should start as when every number is negative. Aim for O(n) time and O(1) space.
Add up the first window
Sum nums[0] to nums[k − 1] and let best_sum start at that sum. This is the only window built from scratch, and as a real window it is a fair candidate for the answer however small it is.
Slide one place at a time
For right from k to n − 1, add nums[right] and subtract nums[right − k]. The number at right − k is the one that just fell out of the window on the left, so the sum now covers indices right − k + 1 to right.
Keep the larger sum
After each move, set best_sum to the larger of itself and the new sum. Because every window has length k, a larger sum always means a larger average, so no division is needed yet.
Divide once at the end
Return best_sum / k as a floating-point number. The best sum belongs to the best window, so this single division gives its average, with the fraction kept.
Code in Python, C++ and Java
k equal to the array length the loop never runs: the whole array is the only window. The best window is indices 0 to 2. Only now divide: 4 ÷ 3 = 1.33333, using floating-point division so the fraction is kept.Common pitfalls
Starting the best sum at 0
best_sum = 0
best_sum = window_sum
When every number is negative, every window sum is below 0, so a 0 start is never beaten. For nums = [-1], k = 1 the code returns 0.0 instead of -1.0, an average no window has.
Integer division in C++ or Java
return bestSum / k;
return (double) bestSum / k;
Two ints divide as integers and drop the fraction before the result is turned into a double. For nums = [1, 2], k = 2 this returns 1.0 instead of 1.5. In Python the same bug is writing // instead of /.
Edge cases
k equals the length of numsThere is only one window. The loop range k to n − 1 is empty, so the answer is the whole array's sum divided by n.
Complexity
Maximum Average Subarray I FAQ
Would dividing on every step give a wrong answer?
No, only a slower one. Floating-point division rounds to the nearest representable value, and rounding never swaps the order of two numbers: if one sum is smaller, its average is smaller or equal after rounding. So the largest average found step by step is the same value as the largest sum divided once. The reason to divide at the end is that it skips n − k divisions.
Can the window sum overflow a 32-bit int?
Not within these limits. A window holds at most 10⁵ numbers of absolute value at most 10⁴, so its sum lies between −10⁹ and 10⁹, below the int limit of about 2.1 × 10⁹. That is why the C++ and Java code use int.
Do prefix sums work here?
Yes. With prefix[i] holding the sum of the first i numbers, the window starting at i sums to prefix[i + k] − prefix[i]. It is also O(n), but it stores an extra array of n + 1 values for no gain on a single fixed k.
What changes in Maximum Average Subarray II?
LeetCode 644 allows any length of at least k, so the best window is no longer a fixed width and sums of different lengths cannot be compared directly. The usual method binary-searches the average: subtract a guess from every number and check whether some window of length at least k has a sum of 0 or more.