7.滑动窗口

滑动窗口:

为了实现找出类表中最大的一组数

先建立变量 right 和 left

用循环将其往后挪移

用 res 记录算到的和

用res—max纪录最大值

a = [1,2,-2,3,5,-2,4]
#a = [1,2,-2,3]
k = 3
left = 0
right = 0 
res = 0
res_max = sum(a[0:k])
while right < len(a):
    res += a[right]
    while right-left > k-1:
        res -= a[left]
        res_max = max(res,res_max)
        left += 1
    right += 1 
print(res_max)

  

 

posted @ 2021-03-14 08:06  学习Python的人  阅读(54)  评论(0编辑  收藏  举报