这道题为简单题
题目:
思路:
我先把前k个数加起来计算平均值,然后遍历列表从索引(k, len(nums)),每次列表向右移动一次就把最左边的的元素减去再加上最新的这个元素,计算总值再求平均值,并与之前的最大值比较,遍历结束后可得最大值。
代码:
1 class Solution(object): 2 def findMaxAverage(self, nums, k): 3 """ 4 :type nums: List[int] 5 :type k: int 6 :rtype: float 7 """ 8 total = 0.0 9 for i in range(k): 10 total += nums[i] 11 m = total / k 12 13 for i in range(k, len(nums)): 14 total = (total-nums[i-k]+nums[i]) 15 m = max(m, total / k) 16 return m
时间: 2024-08-09 14:41:43