Use the following ideas to develop a nonrecursive, linear-time algorithm for the maximum-subarray problem. Start at the left end of the array, and progress toward the right, keeping track of the maximum subarray seen so far. Knowing a maximum subarray of , extend the answer to find a maximum subarray ending at index by using the following observation: a maximum subarray of is either a maximum subarray of or a subarray , for some . Determine a maximum subarray of the form in constant time based on knowing a maximum subarray ending at index .
The idea is to determine whether will be part of the maximum subarray of or not. If it is a part of the maximum subarray, then we will update our returning maximum subarray to include , otherwise we will maintain a temporary sum including in case we encounter a sufficiently large element later which can make the future sum greater than the present sum.
Here is the pseudocode for
FIND-MAXIMUM-SUBARRAY-LINEAR(A, low, high):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 left = 0 right = 0 sum = A[low] temp_sum = 0 temp_left = 0 for i = low to high temp_sum = MAX(A[i], temp_sum + A[i]) if temp_sum > sum sum = temp_sum right = i left = temp_left if temp_sum == A[i] temp_left = i return (left, right, sum)
Line 6 determines whether should be part of the maximum subarray of or not. And in lines 7-9, we update our returning sum and right index if the maximum subarray ending at is indeed the maximum subarrya we have seen so far. In lines 10-11, we store the beginning of the maximum subarray when it contains only one element.
We can measure the performance of this algorithm along with others as described in Exercise 4.1.3 to get the following data which shows that as expected linear algorithm runs way faster than other algorithms: