Maximum Average Subarray - Implementation


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 O(n)O(n) time and O(1)O(1) space (excluding input). Each element is added once and removed at most once.