Maximum Average Subarray I
Find the highest average of any k consecutive numbers, with a fixed-size sliding window.
The problem
You get an integer array nums and an integer k. Among all contiguous subarrays of exactly k elements, find the one with the largest average and return that average. An answer within 10^-5 of the true value is accepted.
Input nums = [3, 8, -2, 6, 7, 1], k = 3
Output 4.66667
The last window, 6 + 7 + 1 = 14, has the largest sum, and 14 / 3 is about 4.66667.
Input nums = [-4, -1, -7], k = 1
Output -1.00000
With k = 1 every number is its own window, so the answer is the largest number.
How to spot the pattern
- The window size is fixed at k and you need the best window.
- Neighbouring windows share k - 1 elements, so you can update the sum instead of recomputing it.
The idea
Every window has the same size k, so the window with the largest sum also has the largest average, and you only need to track sums. Add up the first k numbers, then slide the window one step at a time: add the number that enters on the right and subtract the one that leaves on the left. Divide the best sum by k once, at the end.
Brute force: Add up each of the n - k + 1 windows from scratch, which takes O(n * k) time.
Step by step
- 1Add up the first
knumbers to getwindowSum, and setbest = windowSum. - 2For each
ifromkto n - 1, addnums[i]towindowSumand subtractnums[i - k]. - 3Update
bestwith the newwindowSum. - 4Return
best / kas a floating-point number.
See the pattern move
The sliding window pattern on a small example. Step through it, or press play.
Code
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
window_sum = sum(nums[:k])
best = window_sum
for i in range(k, len(nums)):
window_sum += nums[i] - nums[i - k] # one number enters, one leaves
best = max(best, window_sum)
return best / kComplexity
Time
O(n)
Space
O(1)
Each step adds one number and removes one, however large k is.
Watch out for
- Integer division at the end: in Java and C++, dividing two ints drops the fraction, so convert to double before dividing.
- Starting
bestat 0: when every number is negative, the best sum is below 0 and would never replace it.
Follow-up questions
Why compare sums instead of averages?
All windows share the same k, so the largest sum and the largest average belong to the same window. Sums are exact integers, so you avoid rounding until the single division at the end.
What if the window can be any length of at least k?
That is Maximum Average Subarray II. Binary search on the answer: for a guess x, subtract x from every number and use prefix sums to check whether some window of length k or more has a sum of at least 0.
In Hinglish
Window ka size fix hai, toh average ki jagah sum compare karo; har step pe ek number jodo aur ek ghatao.