643. Maximum Average Subarray I
Given an array consisting of n
integers, find the contiguous subarray of given length k
that has the maximum average value. And you need to output the maximum average value.
给一个数组和窗口k,求一个连续子数组长度为k,和的平均值最大
其实就是滑动窗口前缀和,我们维护一个长度为k的前缀和以及一个全局最大和就行
class Solution(object): def findMaxAverage(self, nums, k): """ :type nums: List[int] :type k: int :rtype: float """ max_sum = 0 current_k_sum = 0 for i in range(k): current_k_sum += nums[i] max_sum = current_k_sum for i in range(k, len(nums), 1): current_k_sum += nums[i] - nums[i - k] max_sum = max(max_sum, current_k_sum) return max_sum * 1.0 / k