643. Maximum Average Subarray I
Easy · solved 2026-09-24 · Open on LeetCode
sliding-windowarray
Time O(n) · Space O(n)
Slicing off the first k elements and zipping the result with the original lines up every element with the one k places ahead. Those are exactly the element leaving the window and the element entering it.
solution.py
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
window = best = sum(nums[:k])
for leaving, entering in zip(nums, nums[k:]):
window += entering - leaving
best = max(best, window)
return best / k