简体   繁体   English

遍历列表以获取 python 中给定范围的最大总和

[英]loop through the list to get Maximum sum for a given range in python

I am a novice in python.我是 python 的新手。 I have a code where I loop through a list to capture maximum sum of numbers for given range k.我有一个代码,我在其中循环遍历列表以捕获给定范围 k 的最大数字总和。 It is working fine but I want it to make it shorter/optimal.它工作正常,但我希望它缩短/优化。 'k' may vary “k”可能会有所不同

numb = [100,33,22,200,333,1000,22]
m=0
k=2
sum1=0
temp=[]
for j in range(len(numb)-(k-1)):
   for i in range(m,k):
     temp.append(numb[i])
   if sum1 < sum(temp):
     sum1 = sum(temp)
   temp=[]
   m+=1
   k+=1
print(sum1)

Ans: 1533 when k = 3 Ans: 1333 when k = 2答案:当 k = 3 时为 1533 答案:当 k = 2 时为 1333

You can start by adding up the first k numbers.您可以先将前k个数字相加。 That is your starting sum and your current max.那是您的起始总和和您当前的最大值。 Then run a sliding window along the list, adding the next number and removing the one that goes out of the window.然后沿着列表运行滑动 window,添加下一个数字并删除 window 之外的数字。

def sum_k(x, k):
    m = s = sum(x[:k])
    for i, a in enumerate(x[k:]):
        b = x[i]  # number to remove
        s += a - b
        m = max(m, s)
    return m


numb = [100, 33, 22, 200, 333, 1000, 22]
print(sum_k(numb, 2), sum_k(numb, 3))

This runs in linear time, which is optimal since you need to at least look at every element in your input.这在线性时间内运行,这是最佳的,因为您至少需要查看输入中的每个元素。

The index, i , in the loop runs from zero to nk-1 , so although we enumerate over x[k:] the indices we pick are from x[0:] , so when we pick b we are picking the number that goes out of the window.循环中的索引i从零运行到nk-1 ,所以虽然我们枚举了x[k:] ,但我们选择的索引来自x[0:] ,所以当我们选择b时,我们选择的数字是在 window 之外。 Meanwhile, a is the new number that comes in.同时, a是进来的新数字。

This is the simplified code you want which takes O(n) of time complexity .这是您想要的简化代码,它需要O(n) 的时间复杂度 This approach is based on Sliding Window Algorithm .这种方法基于滑动 Window 算法

maxSum is the function which takes 2 arguments (array of numbers and k) and returns maximum for any value of k. maxSum是 function,它采用 2 个 arguments(数字和 k 的数组)并返回任何 k 值的最大值。

def maxSum(arr, k):
    # Edge case
    if len(arr) <= k:
        return sum(arr)

    sums = sum(arr[:k]) # sum the first 3 val in arr.
    start = 0 # tell us the first element index whose value is in sums variable
    maximum = sums
    for val in arr[k:]:
        sums = (sums - arr[start]) + val
        # here we first subtracted the start value and then added current value. 
        # Eg. From [1,2,3,4] sums have 1+2+3, but now sums have ( 1+2+3(previous) - 1(start) ) + 4(current)
        # Now check for maximum.
        if sums > maximum:
            maximum = sums
        # now increase start by 1 to make pointer to value '2' and so on.
        start += 1
    
    # return maximum
    return maximum

arr = [100,33,22,200,333,1000,22]
k = 2
print("For k=2: ", maxSum(arr, k))
k = 3
print("For k=3: ", maxSum(arr, k))

Output: Output:

For k=2:  1333
For k=2:  1533

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM