Maximum subarray problem: Difference between revisions

Content deleted Content added
Undid revision 389357847 by 63.238.139.239 (talk). Redundant with pseudocode; Wikipedia is not a code repository
Line 4:
 
==Kadane's algorithm==
Kadane's algorithm consists of a scan through the array values, computing at each position the maximum subarray ending at that position. This subarray is either empty (in which case [[empty sum|its sum is zero]]) or consists of one more element than the maximum subarray ending at the previous position. Thus, the problem can be solved with the following code, expressed here in [[Python (programming language)|Python]]algorithm:
 
<pre>
<source lang="python">
Kadane's Algorithm(array[1..n])
def max_subarray(A):
begin
max_so_far = max_ending_here = 0
(maxSum, maxStartIndex, maxEndIndex) := (-INFINITY, 0, 0)
for x in A:
currentMaxSum := 0
max_ending_here = max(0, max_ending_here + x)
currentStartIndex := 1
max_so_far = max(max_so_far, max_ending_here)
for currentEndIndex := 1 to n do
return max_so_far
currentMaxSum := currentMaxSum + array[currentEndIndex]
</source>
if currentMaxSum > maxSum then
(maxSum, maxStartIndex, maxEndIndex) := (currentMaxSum, currentStartIndex, currentEndIndex)
endif
 
if currentMax < 0 then
currentMax := 0
currentStartIndex := currentEndIndex + 1
endif
endfor
 
return (maxSum, maxStartIndex, maxEndIndex)
end
</pre>
 
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 example of [[dynamic programming]].