Definition
The maximum sum of a contiguous subsequence problem is a problem that finds a contiguous subarray of an array that sum of it will be a maximum.
Solution
Naive solution
In the naive method, every subarray can be computed as it is. Computing sum of subarray takes at most and there could be possible subarrays. As a result, it takes at most $O(n^3)$.
1 |
|
Divide and conquer
Divide and conquer can be applied to this problem either. Notice that to compute optimal solution, the solution that contain middle point should be reconsidered. Therefore, it needs $O(n)$ time for it at each level. As a result, it takses at most $O(n \log n)$. Notice that $T(n) = 2T(n/2) + O(n)$ and it can be applied to Master theorem.
1 |
|
Dynamic programming
Prefix sum
Instead of compute the actual problem, this problem can be converted into the smaller problem. Let’s assume that answer is $\sum\limits_{k=x}^{y} a_k$. Then, answer is $\sum\limits_{k=x}^{y} a_k = \sum\limits_{k=1}^{y} a_k - \sum\limits_{k=1}^{x} a_k$. Which means it’s enough to solve maximum difference in the Prefix sum array. Which is much easier to be solved. Notice that to save space, there is no physical Prefix sum array in the code below.
1 |
|
Max Ends At
Instead of using Prefix sum, algorithm can compute the maximum value that will ends at $i$th elements. In this case, it is obvious that it just decide whether it will expend to the next element or not because advantage of choosing subarray from ahead should be positive.
1 |
|