Definition
The maximum subarray problem asks for the contiguous subarray of an array whose sum is the largest.
Solutions
Naive Solution
The brute-force approach tries all $O(n^2)$ subarrays, each taking up to $O(n)$ to compute. This gives a total time of $O(n^3)$.
1 | |
Divide and Conquer
Divide and conquer also applies here. At each recursive level, we must consider subarrays crossing the midpoint, which takes $O(n)$. This gives $T(n) = 2T(n/2) + O(n)$, which by the Master’s Theorem yields $O(n \log n)$.
1 | |
Dynamic Programming
Prefix Sum
The problem can be reformulated: if the answer is $\sum\limits_{k=x}^{y} a_k$, then it equals the difference of two prefix sums: $\sum\limits_{k=1}^{y} a_k - \sum\limits_{k=1}^{x-1} a_k$. So it suffices to find the maximum difference in the prefix sum array, which is straightforward. The code below avoids storing the full prefix sum array to save space.
1 | |
Max Ends At (Kadane’s Algorithm)
Alternatively, we compute the maximum subarray sum ending at each position $i$. The key observation is that extending the subarray to include the previous element is worthwhile only if the running sum is positive.
1 | |