Skip to content

visual walkthrough

Maximum Average Subarray I

EasyFixed-size WindowReported at: Meta

The textbook fixed window: add the new element, drop the old one.

Solve on LeetCode

The idea

Windows of the same size overlap almost completely: moving one step right drops one number and adds one. So the new sum is the old sum, plus the number that enters, minus the number that leaves.

The maximum average is just the maximum sum divided by k.

Complexity

approachtimespace
Re-add every windowO(n · k)O(1)
Slide the sumO(n)O(1)

More walkthroughs