我试图理解这个问题的解决方案:“给定一个数字序列,找到这些数字的连续子序列的最大总和。”我在下面引用了一个解决方案和解释。连续子序列的最大和为零?
我不明白的是,在“maxendinghere = max(maxendinghere + s,0)”这一行中,为什么maxendinghere会是零?
def max_sum_subsequence(seq):
maxsofar = 0
maxendinghere = 0
for s in seq:
# invariant: maxendinghere and maxsofar are accurate
# are accurate up to s
maxendinghere = max(maxendinghere + s, 0)
maxsofar = max(maxsofar, maxendinghere)
return maxsofar
从网站上的解释是“好了,基本上maxendinghere是什么积累的子序列 - 它不断滚动的下一个元素到自身如果这种积累和以往任何时候都变得消极,我们知道,子,其中,ends-在这里我们目前的跟踪比空的子序列更糟糕 - 它重新启动 - 这里;所以我们可以重置我们的子序列累加器,并且循环不变的第一个子句仍然成立。
我不明白的是,让我们说我的顺序是2 -3 4:为什么maxendinghere会是零?没有任何总和为零的子序列。
(行情从:http://wordaligned.org/articles/the-maximum-subsequence-problem)