Kadane 的算法跟踪在当前点结束的序列的最大值,以及到目前为止看到的最大值。
这是基于维基百科页面的 Python 实现:
def kadane(A):
max_ending_here = max_so_far = 0
for x in A:
max_ending_here = max([x,0,max_ending_here+x])
max_so_far = max(max_so_far,max_ending_here)
return max_so_far
我们可以通过添加两个变量来修改算法以跟踪此类序列的计数:
- count_with_max_ending_here计算在当前点结束且总和为 max_ending_here 的序列数
- count_with_max以最大值计算到目前为止找到的序列数
Kadane 的算法可以直接更改以跟踪这些变量,同时保持 O(n) 复杂度:
def kadane_count(A):
max_ending_here = max_so_far = 0
count_with_max_ending_here = 0 # Number of nontrivial sequences that sum to max_ending_here
count_with_max = 0
for i,x in enumerate(A):
new_max = max_ending_here+x
if new_max>=0:
if count_with_max_ending_here==0:
# Start a nontrivial sequence here
count_with_max_ending_here=1
elif max_ending_here==0:
# Can choose to carry on a nontrivial sequence, or start a new one here
count_with_max_ending_here += 1
max_ending_here = new_max
else:
count_with_max_ending_here = 0
max_ending_here = 0
if max_ending_here > max_so_far:
count_with_max = count_with_max_ending_here
max_so_far = max_ending_here
elif max_ending_here == max_so_far:
count_with_max += count_with_max_ending_here
return count_with_max
for A in [ [0,0,0,1],[0,0,0],[2,0,-2,2] ]:
print kadane(A),kadane_count(A)