643. Maximum Average Subarray I
2021-02-04 本文已影响0人
morningstarwang
Ref: https://leetcode-cn.com/problems/maximum-average-subarray-i/
这道题思路比较清晰,滑动窗口,维持窗口的sum,每次减去滑动前第一个元素,加上滑动后最后一个元素,代码实现如下:
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
m_sum = sum(nums[:k])
result = m_sum
for i, j in zip(nums[:-k], nums[k:]):
m_sum -= i
m_sum += j
if m_sum > result:
result = m_sum
return result / k