Use the following ideas to develop a non-recursive, 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 \(A[1 \dots j]\), extend the answer to find a maximum subarray ending at index \(j + 1\) by using the following observation: a maximum subarray of \(A[1 \dots j + 1]\) is either a maximum subarray of \(A[1 \dots j]\) or a subarray \(A[i \dots j + 1]\), for some \(1 \le i \le j + 1\). Determine a maximum subarray of the form \(A[i \dots j + 1]\) in constant time based on knowing a maximum subarray ending at index \(j\).
The idea is to determine whether \(A[j + 1]\) will be part of the maximum subarray of \(A[1 \dots j + 1]\) or not. If it is a part of the maximum subarray, then we will update our maximum subarray to include \(A[j + 1]\), otherwise we will maintain a temporary sum including \(A[j + 1]\) in case we encounter a sufficiently large element later which can make the future sum greater than the present sum.
In other words, maintain two sum: a maximum subarray ending at current element, and maximum subarray so far.
In line 7, we update our current sum involving current element. And in lines 8-11, we update our best subarray, if required. In lines 12-14, we reset current running sum if it is negative.
A python implementation of this pseudocode is available at the bottom of the page.
We can measure the performance of this algorithm along with others as described in Exercise 4.1.3. As expected the linear algorithm runs much much faster than other algorithms (running times are in microseconds):
The C++ implementation to generate this data can be downloaded from here.
And here is a visual representation of the runtime comparison.
As you can see the brute force run time, \(\Theta(n^2)\), very closely resembles a quadratic curve. Runtime of recursive method is \(\Theta(n \lg n)\) and for linear it is \(\Theta(n)\), the difference between them also can be seen clearly, although both resembles linear curve. That ambiguity will reduce if we can create graph for much higher input size, e.g. \(n = 1000\).