gpt4 book ai didi

algorithm - 使用 Kadane 算法查找数组中最大和子数组的数量

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:18:25 24 4
gpt4 key购买 nike

Kadane 算法 ( http://en.wikipedia.org/wiki/Maximum_subarray_problem ) 用于查找一维数字数组中连续子数组的最大和。

现在,如何使用它来找出具有相同最大和的此类序列的数量?可以对算法进行哪些修改以计算此类序列..

例如:

0 0 0 1     -> (largest sum = 1); 4 sequences  { (0,0,0,1), (0,0,1), (0,1) , (1) }

0 0 0 -> (largest sum = 0); 6 sequences { (0,0,0), (0,0), (0,0), (0), (0), (0) }

2 0 -2 2 -> (largest sum = 2); 4 sequences { (2), (2,0), (2,0,-2, 2), (2) }

最佳答案

Kadane 的算法跟踪在当前点结束的序列的最大值,以及到目前为止看到的最大值。

这里是一个基于the wikipedia page的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)

关于algorithm - 使用 Kadane 算法查找数组中最大和子数组的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17026613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com