其他分享
首页 > 其他分享> > LeetCode #643. Maximum Average Subarray I

LeetCode #643. Maximum Average Subarray I

作者:互联网

题目

643. Maximum Average Subarray I


解题方法

利用滑动窗口的思想,先计算数组中前k个数的总和knumsum,再设置i从第k个数开始,每次将knumsum加上第i个数,减去第i-k个数,并记录其最大值,最后返回最大值/k即可。


代码

class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        knumsum = 0
        for i in range(k):
            knumsum += nums[i]
        rat = knumsum
        for i in range(k, len(nums)):
            knumsum += nums[i] - nums[i-k]
            rat = max(rat, knumsum)
        return rat/k

标签:nums,knumsum,Average,个数,rat,643,Subarray,range
来源: https://www.cnblogs.com/RatsCommander/p/13920487.html