Kadane's algorithm(Kadane算法)

来源:互联网 发布:淘宝买家3心要多少信誉 编辑:程序博客网 时间:2024/06/05 07:09

在刷LeetCode的时候遇到了。。查了一下维百,Kadane是卡内基梅隆大学的教授,这个算法是为了解决最大子序列的和(maximum subarray)提出的。

以下资料全部来自维基百科:

1、什么是maximum subarray problem?

In computer science, the maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers which has the largest sum. For example, for the sequence of values −2, 1, −3, 4, −1, 2, 1, −5, 4; the contiguous subarray with the largest sum is 4, −1, 2, 1, with sum 6.

The problem was first posed by Ulf Grenander of Brown University in 1977, as a simplified model for maximum likelihood estimation of patterns in digitized images. A linear time algorithm was found soon afterwards by Jay Kadane of Carnegie Mellon University (Bentley 1984).

2、算法的详细介绍:

Kadane's algorithm begins with a simple inductive question: if we know the maximum subarray sum ending at position {\displaystyle i}i, what is the maximum subarray sum ending at position {\displaystyle i+1}i+1? The answer turns out to be relatively straightforward: either the maximum subarray sum ending at position {\displaystyle i+1}i+1 includes the maximum subarray sum ending at position {\displaystyle i}i as a prefix, or it doesn't. Thus, we can compute the maximum subarray sum ending at position {\displaystyle i}ifor all positions {\displaystyle i}i by iterating once over the array. As we go, we simply keep track of the maximum sum we've ever seen. Thus, the problem can be solved with the following code, expressed here in Python:

def max_subarray(A):    max_ending_here = max_so_far = A[0]    for x in A[1:]:        max_ending_here = max(x, max_ending_here + x)        max_so_far = max(max_so_far, max_ending_here)    return max_so_far
The algorithm can also be easily modified to keep track of the starting and ending indices of the maximum subarray (when max_so_far changes) as well as the case where we want to allow zero-length subarrays (with implicit sum 0) if all elements are negative.

Because of the way this algorithm uses optimal substructures (the maximum subarray ending at each position is calculated in a simple way from a related but smaller and overlapping subproblem: the maximum subarray ending at the previous position) this algorithm can be viewed as a simple/trivial example of dynamic programming.

算法的时间复杂度是O(n)。

更多的资料可以参考:https://en.wikipedia.org/wiki/Maximum_subarray_problem