function findMaxAverage(nums, k):
windowSum = sum of nums[0..k-1]
maxSum = windowSum
for i from k to nums.length - 1:
windowSum += nums[i] - nums[i - k]
maxSum = max(maxSum, windowSum)
return maxSum / k
This runs in time and space (excluding input). Each element is added once and removed at most once.