topic
input:[ 1, 12, -5, -6, 50, 3 ],4
output:12.75
Ideas
Sliding the window, first add the previous sum to the next value of j, and then subtract the first value to form a valid window.
Code
def findMaxnumsverage(n,w):
windows_sum = 0
for i in range(w):
windows_sum += n[i]
res = windows_sum
for j in range(w,len(n)):
windows_sum = windows_sum + n[j] - n[j-w]
res = max(res,windows_sum)
return res/w
nums = [ 1, 12, -5, -6, 50, 3 ]
a = findMaxnumsverage(nums, 4)
print(a)