SDE & MLE Prep

643. Maximum Average Subarray I

Problem

Return the largest average of any contiguous subarray of exactly length k.

Example: nums = [1,12,-5,-6,50,3], k = 4 → 12.75

Fixed window of size k: add the new element, subtract the one leaving, track the max sum.

Complexity: O(n).

class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        s = best = sum(nums[:k])
        for i in range(k, len(nums)):
            s += nums[i] - nums[i - k]
            best = max(best, s)
        return best / k