[英]Find maximum sum of sublist in list of positive integers under O(n^2) of specified length Python 3.5
For one of my programming questions, I am required to define a function that accepts two variables, a list of length l and an integer w. 对于我的编程问题之一,我需要定义一个函数,该函数接受两个变量,即长度为l的列表和整数w。 I then have to find the maximum sum of a sublist with length w within the list. 然后,我必须找到列表中长度为w的子列表的最大和。
Conditions: 条件:
1<=w<=l<=100000 1 <= W <= 1 <= 10万
Each element in the list ranges from [1, 100] 列表中的每个元素的范围是[1,100]
Currently, my solution works in O(n^2) (correct me if I'm wrong, code attached below), which the autograder does not accept, since we are required to find an even simpler solution. 目前,我的解决方案在O(n ^ 2)(如果我错了,请纠正我,下面的代码)中工作,自动分级机不接受,因为我们需要找到一个更简单的解决方案。
My code: 我的代码:
def find_best_location(w, lst):
best = 0
n = 0
while n <= len(lst) - w:
lists = lst[n: n + w]
cur = sum(lists)
best = cur if cur>best else best
n+=1
return best
If anyone is able to find a more efficient solution, please do let me know! 如果有人能够找到更有效的解决方案,请告诉我! Also if I computed my big-O notation wrongly do let me know as well! 另外,如果我错误地计算了big-O表示法,请也告诉我!
Thanks in advance! 提前致谢!
1) Find sum current
of first w
elements, assign it to best
. 1)找到和current
第一的w
元素,将其分配到best
。
2) Starting from i = w
: current = current + lst[i]-lst[iw]
, best = max(best, current)
. 2)从i = w
: current = current + lst[i]-lst[iw]
, best = max(best, current)
。
3) Done. 3)完成。
Your solution is indeed O(n^2)
(or O(n*W)
if you want a tighter bound) 您的解决方案的确是O(n^2)
(或者,如果您想更严格地限制,则为O(n*W)
)
You can do it in O(n) by creating an aux array sums
, where: 您可以通过创建aux数组sums
在O(n)中执行以下操作:
sums[0] = l[0]
sums[i] = sums[i-1] + l[i]
Then, by iterating it and checking sums[i] - sums[iW]
you can find your solution in linear time 然后,通过迭代并检查sums[i] - sums[iW]
您可以在线性时间内找到解决方案
You can even calculate sums
array on the fly to reduce space complexity, but if I were you, I'd start with it, and see if I can upgrade my solution next. 您甚至可以即时计算sums
数组以减少空间复杂性,但是如果您是我,我将从它开始,然后看看是否可以升级我的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.