Problem Statement
Maximum Average Subarray I
You are given a list of whole numbers called nums, and a number k. Your job is to look at every run of k numbers in a row (a contiguous run means the numbers sit right next to each other, no gaps and no skipping). For each run of k numbers, you find its average. You return the biggest average you can find.
Signals to notice
Brute force first
Calculate sum for every subarray of size k. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.
The key insight
Slide a window of size k: add the new element, subtract the old one. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.
Trace it on nums=[1,12,-5,-6,50,3], k=4
Init first window nums[0..3]=[1,12,-5,-6]: window_sum=2, max_sum=2 i=4: window_sum += nums[4]-nums[0] = 50-1 -> window_sum=51; max_sum=max(2,51)=51 (window [12,-5,-6,50]) i=5: window_sum += nums[5]-nums[1] = 3-12 -> window_sum=42; max_sum=max(51,42)=51 (window [-5,-6,50,3]) Loop ends; max_sum=51 Return max_sum/k = 51/4 = 12.75
What must stay true
The window sum is always the sum of exactly k consecutive elements. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.
Shape of the loop
window_sum = sum(nums[0..k-1])
max_sum = window_sum
for i from k to n-1:
window_sum += nums[i] - nums[i-k] # slide: add new, drop old
max_sum = max(max_sum, window_sum)
return max_sum / kPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Off-by-one when initializing the first window — sum exactly k elements first. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.