maximum-average-subarray-sliding-window

Maximum Average Subarray I (LeetCode 643): A Fixed Sliding Window

Given an integer array nums and an integer k, find the contiguous subarray of length k with the largest average and return that average.

Idea: Averages over the same length compare exactly like sums, so track the best window sum and divide once at the end. Slide the window: add the entering element, subtract the leaving one.

def findMaxAverage(nums, k):

s = sum(nums[:k])

best = s

for i in range(k, len(nums)):

s += nums[i] - nums[i - k]

best = max(best, s)

return best / k

Complexity: O(n) time, O(1) extra space, versus O(n*k) for recomputing every window.

Interview notes: Point out why you divide only once (fewer floating point operations, no precision drift) and mention the edge case k == len(nums), where the loop never runs.

If you want to rehearse explaining solutions like this under time pressure, AI interview assistant is something I help build (disclosure: I work on Linkjob AI).

Made on mmm