Problem statement

https://leetcode.com/problems/maximum-average-subarray-i/

Solution

Just do what is asked, using sliding window (alternative solution is to use cumulative sums).

Complexity

Time complexity is O(n), space complexity is O(1).

Code

class Solution:
    def findMaxAverage(self, nums, k):
        sm = sum(nums[:k])
        max_av = sm
        for i in range(k, len(nums)):
            sm += (nums[i] - nums[i-k])
            max_av = max(max_av, sm)
        return max_av/k