Problem Statement
leetcode problem link
Brute Force [Accepted]
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
l, r = 0, 0
N = len(nums)
curr_sum = 0
res = float('-inf')
for r in range(N):
curr_sum += nums[r]
if r - l + 1 >= k:
res = max(res, curr_sum / k)
curr_sum -= nums[l]
l += 1
return res
Editorial
Sliding window
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
curr = 0
for i in range(k):
curr += nums[i]
ans = curr
for i in range(k, len(nums)):
curr += nums[i] - nums[i - k]
ans = max(ans, curr)
return ans / k