Algorithm 关于卡丹的困惑’;s算法?
我找到了寻找连续子阵最大和的最优解。还有一种叫做卡丹算法的算法。这是我在Geeksforgek上找到的psedoocodeAlgorithm 关于卡丹的困惑’;s算法?,algorithm,time-complexity,Algorithm,Time Complexity,我找到了寻找连续子阵最大和的最优解。还有一种叫做卡丹算法的算法。这是我在Geeksforgek上找到的psedoocode Initialize: max_so_far = 0 max_ending_here = 0 Loop for each element of the array (a) max_ending_here = max_ending_here + a[i] (b) if(max_ending_here < 0)
Initialize:
max_so_far = 0
max_ending_here = 0
Loop for each element of the array
(a) max_ending_here = max_ending_here + a[i]
(b) if(max_ending_here < 0)
max_ending_here = 0
(c) if(max_so_far < max_ending_here)
max_so_far = max_ending_here
return max_so_far
初始化:
到目前为止的最大值=0
此处的最大值=0
数组中每个元素的循环
(a) max_ending_here=max_ending_here+a[i]
(b) if(此处的最大值小于0)
此处的最大值=0
(c) 如果(最大值到目前为止<最大值到此结束)
max\u so\u far=max\u ending\u此处
返回到目前为止的最大值
我不明白的部分是(b),为什么这里的max_ending小于0时,max_ending设置为0??这背后的直觉是什么?如果第(b)部分中的max\u ending\u小于0,这意味着使用此元素的最大和小于0。有一个比这里结束的更好的总和,就是只取一个长度为0的子数组。这就是我们在(b)部分所做的
基本上,如果我们在第(b)部分中输入
if
,我们将丢弃所有以前的元素并从头开始子阵列。您希望重置最大值,因为任何可能会偏移最大值的负数组元素
比如说,
2 3 -6 4 2
在元素
-6
,如果不在此处重置最大值,则将-1
的最大值带入下一次迭代。“有一个比在此处结束的总和更好的总和,即只取一个长度为0的子数组”: