Open In App

Maximum Sum SubArray using Divide and Conquer | Set 2

Last Updated : 10 Nov, 2021
Comments
Improve
Suggest changes
7 Likes
Like
Report

Given an array arr[] of integers, the task is to find the maximum sum sub-array among all the possible sub-arrays.
Examples: 
 

Input: arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4} 
Output:
{4, -1, 2, 1} is the required sub-array.
Input: arr[] = {2, 2, -2} 
Output:
 


 


Approach: Till now we are only aware of Kadane's Algorithm which solves this problem in O(n) using dynamic programming. 
We had also discussed a divide and conquer approach for maximum sum subarray in O(N*logN) time complexity.
The following approach solves it using Divide and Conquer approach which takes the same time complexity of O(n).
Divide and conquer algorithms generally involves dividing the problem into sub-problems and conquering them separately. For this problem we maintain a structure (in cpp) or class(in java or python) which stores the following values: 
 

  1. Total sum for a sub-array.
  2. Maximum prefix sum for a sub-array.
  3. Maximum suffix sum for a sub-array.
  4. Overall maximum sum for a sub-array.(This contains the max sum for a sub-array).


During the recursion(Divide part) the array is divided into 2 parts from the middle. The left node structure contains all the above values for the left part of array and the right node structure contains all the above values. Having both the nodes, now we can merge the two nodes by computing all the values for resulting node. 
The max prefix sum for the resulting node will be maximum value among the maximum prefix sum of left node or left node sum + max prefix sum of right node or total sum of both the nodes (which is possible for an array with all positive values). 
Similarly the max suffix sum for the resulting node will be maximum value among the maximum suffix sum of right node or right node sum + max suffix sum of left node or total sum of both the nodes (which is again possible for an array with all positive values). 
The total sum for the resulting node is the sum of both left node and right node sum. 
Now, the max subarray sum for the resulting node will be maximum among prefix sum of resulting node, suffix sum of resulting node, total sum of resulting node, maximum sum of left node, maximum sum of right node, sum of maximum suffix sum of left node and maximum prefix sum of right node. 
Here the conquer part can be done in O(1) time by combining the result from the left and right node structures.
Below is the implementation of the above approach:
 

C++
Java Python3 C# JavaScript

Output: 

Answer is 7


Time Complexity: The getMaxSumSubArray() recursive function generates the following recurrence relation. 
T(n) = 2 * T(n / 2) + O(1) note that conquer part takes only O(1) time. So on solving this recurrence using Master's Theorem we get the time complexity of O(n).
 


Next Article

Similar Reads