LeetCode #643 Easy

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.

Constraints
  • n == nums.length
  • 1 <= k <= n <= 10⁵
  • -10⁴ <= nums[i] <= 10⁴
arraysliding-window
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findMaxAverage(self, nums, k):
▶3 window_sum = sum(nums[:k])
▶4 best_sum = window_sum
▶5 for right in range(k, len(nums)):
▶6 window_sum += nums[right] - nums[right - k]
▶7 best_sum = max(best_sum, window_sum)
▶8 return best_sum / k
10121−52−6350435window sum1+12+−5+−6=2best sumfirst 4 numbers add up to 2
k4window width
window_sum2indices 0 to 3
The first window is the only one added up from scratch: indices 0 to 3 sum to 2. Every later window will reuse this sum instead of adding 4 numbers again.
10121−52−6350435window sum2best sum2best sum starts at 2
best_sum2first real window
The first window is a real candidate, so the best sum starts at 2. Later windows replace it only if their sum is larger.
10out121−52−63504in35window sum2−1+50=51best sum2drop 1, add 50 → sum 51
right4
out1index 0
in50index 4
window_sum51
The window moves to indices 1 to 4. It shares 3 numbers with the previous window, so only two values change: 1 leaves on the left and 50 arrives on the right. 2 − (1) + (50) = 51.
10121−52−6350435window sum51best sum51>2→5151 beats 2 → new best
best_sum51
The new sum 51 is larger than the best so far (2). Every window has 4 numbers, so a larger sum is a larger average: this window is the new best.
10121out−52−6350435inwindow sum51−12+3=42best sum51drop 12, add 3 → sum 42
right5
out12index 1
in3index 5
window_sum42
The window moves to indices 2 to 5. It shares 3 numbers with the previous window, so only two values change: 12 leaves on the left and 3 arrives on the right. 51 − (12) + (3) = 42.
10121−52−6350435window sum42best sum42≤51→5142 is not above 51 → keep best
best_sum51
The new sum 42 is not larger than the best so far (51), so this window cannot have a larger average. The best stays.
10121−52−6350435window sum42best sum51÷4=12.75answer 12.75
best_sum51
average12.75
Every window has been checked. The best window is indices 1 to 4. Only now divide: 51 ÷ 4 = 12.75, using floating-point division so the fraction is kept.
05

Common pitfalls

Starting the best sum at 0

✗ Wrong
best_sum = 0
✓ Right
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

✗ Wrong
return bestSum / k;
✓ Right
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 /.

06

Edge cases

k equals the length of nums

There 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.

07

Complexity

Time
O(n)
Space
O(1)
The first window costs k additions, and each of the remaining n − k moves costs one addition and one subtraction. Only the running sum and the best sum are stored.
08

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.