Maximum contiguous subsequence sum C++

Maximum contiguous subsequence sum problem

Given an array of N integers. The array is expected to contain positive as well as negative numbers. Find the maximum contiguous subsequence sum (MCSS) of the array. For example the MCSS of {2, -4, 1, 2} is 3 which is the sum of the subsequence {1, 2}. A brute force approach requires 3 nested loops with time complexity of O(N3). Write code to solve this problem with time complexity of O(nlogn). Hint: use divide and concur technique.

Maximum contiguous subsequence sum algorithm

finding maximum contiguous subsequence sum: split the array into two halfs. Note that one of the following three cases must hold:

1. The max subsequence is in the left half.
2. The max subsequence is in the right half.
3. The max subsequence begins in the left half and ends in the right half.

Once the above values are computed just take the maximum of the three values as the MCSS. The base case of the recursion is when we have only one element. In that case the LCSS is the element itself if it is positive otherwise the LCSS is 0. The tricky part is computing the LCSS in the third case. This is done by finding the maximum sum to the left of the center and the maximum sum to the right of the center then adding both values together.

Code

Here is the maximum contiguous subsequence sum in C++ code

Please use the comments section below for questions, corrections or feedback. Thanks for reading.

Add a Comment

Your email address will not be published. Required fields are marked *