Content deleted Content added
I don't see how expanding the pseudocode threefold is an improvement; undo. |
Tellarunbose (talk | contribs) Undid revision 399282159 by David Eppstein (talk) . An algorithm is readable to more audience than a python code. |
||
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
<pre>
Kadane's Algorithm(array[1..n])
begin
(maxSum, maxStartIndex, maxEndIndex) := (-INFINITY, 0, 0)
currentMaxSum := 0
currentStartIndex := 1
for currentEndIndex := 1 to n do
currentMaxSum := currentMaxSum + array[currentEndIndex]
if currentMaxSum > maxSum then
(maxSum, maxStartIndex, maxEndIndex) := (currentMaxSum, currentStartIndex, currentEndIndex)
endif
if currentMaxSum < 0 then
currentMaxSum := 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]].
|