Maximum Sum SubArray using Divide and Conquer | Set 2
Last Updated :
11 Jul, 2025
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: 6
{4, -1, 2, 1} is the required sub-array.
Input: arr[] = {2, 2, -2}
Output: 4
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:
- Total sum for a sub-array.
- Maximum prefix sum for a sub-array.
- Maximum suffix sum for a sub-array.
- 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++
// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;
struct Node {
// To store the maximum sum
// for a sub-array
long long _max;
// To store the maximum prefix
// sum for a sub-array
long long _pre;
// To store the maximum suffix
// sum for a sub-array
long long _suf;
// To store the total sum
// for a sub-array
long long _sum;
};
// Function to create a node
Node getNode(long long x){
Node a;
a._max = x;
a._pre = x;
a._suf = x;
a._sum = x;
return a;
}
// Function to merge the 2 nodes left and right
Node merg(const Node &l, const Node &r){
// Creating node ans
Node ans ;
// Initializing all the variables:
ans._max = ans._pre = ans._suf = ans._sum = 0;
// The max prefix sum of ans Node is maximum of
// a) max prefix sum of left Node
// b) sum of left Node + max prefix sum of right Node
// c) sum of left Node + sum of right Node
ans._pre = max({l._pre, l._sum+r._pre, l._sum+r._sum});
// The max suffix sum of ans Node is maximum of
// a) max suffix sum of right Node
// b) sum of right Node + max suffix sum of left Node
// c) sum of left Node + sum of right Node
ans._suf = max({r._suf, r._sum+l._suf, l._sum+r._sum});
// Total sum of ans Node = total sum of left Node + total sum of right Node
ans._sum = l._sum + r._sum;
// The max sum of ans Node stores the answer which is the maximum value among:
// prefix sum of ans Node
// suffix sum of ans Node
// maximum value of left Node
// maximum value of right Node
// prefix value of right Node + suffix value of left Node
ans._max = max({ans._pre, ans._suf, ans._sum,l._max, r._max, l._suf+r._pre});
// Return the ans Node
return ans;
}
// Function for calculating the
// max_sum_subArray using divide and conquer
Node getMaxSumSubArray(int l, int r, vector<long long> &ar){
if (l == r) return getNode(ar[l]);
int mid = (l + r) >> 1;
// Call method to return left Node:
Node left = getMaxSumSubArray(l, mid, ar);
// Call method to return right Node:
Node right = getMaxSumSubArray(mid+1, r, ar);
// Return the merged Node:
return merg(left, right);
}
// Driver code
int main(){
vector<long long> ar = {-2, -5, 6, -2, -3, 1, 5, -6};
int n = ar.size();
Node ans = getMaxSumSubArray(0, n-1, ar);
cout << "Answer is " << ans._max << "\n";
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
static class Node
{
// To store the maximum sum
// for a sub-array
int _max;
// To store the maximum prefix
// sum for a sub-array
int _pre;
// To store the maximum suffix
// sum for a sub-array
int _suf;
// To store the total sum
// for a sub-array
int _sum;
};
// Function to create a node
static Node getNode(int x)
{
Node a = new Node();
a._max = x;
a._pre = x;
a._suf = x;
a._sum = x;
return a;
}
// Function to merge the 2 nodes left and right
static Node merg(Node l, Node r)
{
// Creating node ans
Node ans = new Node();
// Initializing all the variables:
ans._max = ans._pre = ans._suf = ans._sum = 0;
// The max prefix sum of ans Node is maximum of
// a) max prefix sum of left Node
// b) sum of left Node + max prefix sum of right Node
// c) sum of left Node + sum of right Node
ans._pre = Arrays.stream(new int[]{l._pre, l._sum+r._pre,
l._sum+r._sum}).max().getAsInt();
// The max suffix sum of ans Node is maximum of
// a) max suffix sum of right Node
// b) sum of right Node + max suffix sum of left Node
// c) sum of left Node + sum of right Node
ans._suf = Arrays.stream(new int[]{r._suf, r._sum+l._suf,
l._sum+r._sum}).max().getAsInt();
// Total sum of ans Node = total sum of
// left Node + total sum of right Node
ans._sum = l._sum + r._sum;
// The max sum of ans Node stores
// the answer which is the maximum value among:
// prefix sum of ans Node
// suffix sum of ans Node
// maximum value of left Node
// maximum value of right Node
// prefix value of right Node + suffix value of left Node
ans._max = Arrays.stream(new int[]{ans._pre,
ans._suf,
ans._sum,
l._max, r._max,
l._suf+r._pre}).max().getAsInt();
// Return the ans Node
return ans;
}
// Function for calculating the
// max_sum_subArray using divide and conquer
static Node getMaxSumSubArray(int l, int r, int []ar)
{
if (l == r) return getNode(ar[l]);
int mid = (l + r) >> 1;
// Call method to return left Node:
Node left = getMaxSumSubArray(l, mid, ar);
// Call method to return right Node:
Node right = getMaxSumSubArray(mid + 1, r, ar);
// Return the merged Node:
return merg(left, right);
}
// Driver code
public static void main(String[] args)
{
int []ar = {-2, -5, 6, -2, -3, 1, 5, -6};
int n = ar.length;
Node ans = getMaxSumSubArray(0, n - 1, ar);
System.out.print("Answer is " + ans._max + "\n");
}
}
// This code is contributed by shikhasingrajput
Python3
# Python3 implementation of the approach
class Node:
def __init__(self, x):
# To store the maximum sum for a sub-array
self._max = x
# To store the maximum prefix sum for a sub-array
self._pre = x
# To store the maximum suffix sum for a sub-array
self._suf = x
# To store the total sum for a sub-array
self._sum = x
# Function to merge the 2 nodes left and right
def merg(l, r):
# Creating node ans
ans = Node(0)
# The max prefix sum of ans Node is maximum of
# a) max prefix sum of left Node
# b) sum of left Node + max prefix sum of right Node
# c) sum of left Node + sum of right Node
ans._pre = max(l._pre, l._sum+r._pre, l._sum+r._sum)
# The max suffix sum of ans Node is maximum of
# a) max suffix sum of right Node
# b) sum of right Node + max suffix sum of left Node
# c) sum of left Node + sum of right Node
ans._suf = max(r._suf, r._sum+l._suf, l._sum+r._sum)
# Total sum of ans Node = total sum of
# left Node + total sum of right Node
ans._sum = l._sum + r._sum
# The max sum of ans Node stores the answer
# which is the maximum value among:
# prefix sum of ans Node
# suffix sum of ans Node
# maximum value of left Node
# maximum value of right Node
# prefix value of left Node + suffix value of right Node
ans._max = max(ans._pre, ans._suf, ans._sum,
l._max, r._max, l._suf+r._pre)
# Return the ans Node
return ans
# Function for calculating the
# max_sum_subArray using divide and conquer
def getMaxSumSubArray(l, r, ar):
if l == r: return Node(ar[l])
mid = (l + r) // 2
# Call method to return left Node:
left = getMaxSumSubArray(l, mid, ar)
# Call method to return right Node:
right = getMaxSumSubArray(mid+1, r, ar)
# Return the merged Node:
return merg(left, right)
# Driver code
if __name__ == "__main__":
ar = [-2, -5, 6, -2, -3, 1, 5, -6]
n = len(ar)
ans = getMaxSumSubArray(0, n-1, ar)
print("Answer is", ans._max)
# This code is contributed by Rituraj Jain
C#
// C# implementation of the approach
using System;
using System.Linq;
public class GFG
{
class Node
{
// To store the maximum sum
// for a sub-array
public int _max;
// To store the maximum prefix
// sum for a sub-array
public int _pre;
// To store the maximum suffix
// sum for a sub-array
public int _suf;
// To store the total sum
// for a sub-array
public int _sum;
};
// Function to create a node
static Node getNode(int x)
{
Node a = new Node();
a._max = x;
a._pre = x;
a._suf = x;
a._sum = x;
return a;
}
// Function to merge the 2 nodes left and right
static Node merg(Node l, Node r)
{
// Creating node ans
Node ans = new Node();
// Initializing all the variables:
ans._max = ans._pre = ans._suf = ans._sum = 0;
// The max prefix sum of ans Node is maximum of
// a) max prefix sum of left Node
// b) sum of left Node + max prefix sum of right Node
// c) sum of left Node + sum of right Node
ans._pre = (new int[]{l._pre, l._sum+r._pre,
l._sum+r._sum}).Max();
// The max suffix sum of ans Node is maximum of
// a) max suffix sum of right Node
// b) sum of right Node + max suffix sum of left Node
// c) sum of left Node + sum of right Node
ans._suf = (new int[]{r._suf, r._sum+l._suf,
l._sum+r._sum}).Max();
// Total sum of ans Node = total sum of
// left Node + total sum of right Node
ans._sum = l._sum + r._sum;
// The max sum of ans Node stores
// the answer which is the maximum value among:
// prefix sum of ans Node
// suffix sum of ans Node
// maximum value of left Node
// maximum value of right Node
// prefix value of right Node + suffix value of left Node
ans._max = (new int[]{ans._pre,
ans._suf,
ans._sum,
l._max, r._max,
l._suf+r._pre}).Max();
// Return the ans Node
return ans;
}
// Function for calculating the
// max_sum_subArray using divide and conquer
static Node getMaxSumSubArray(int l, int r, int []ar)
{
if (l == r) return getNode(ar[l]);
int mid = (l + r) >> 1;
// Call method to return left Node:
Node left = getMaxSumSubArray(l, mid, ar);
// Call method to return right Node:
Node right = getMaxSumSubArray(mid + 1, r, ar);
// Return the merged Node:
return merg(left, right);
}
// Driver code
public static void Main(String[] args)
{
int []ar = {-2, -5, 6, -2, -3, 1, 5, -6};
int n = ar.Length;
Node ans = getMaxSumSubArray(0, n - 1, ar);
Console.Write("Answer is " + ans._max + "\n");
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// Javascript implementation of the approach
class Node {
constructor()
{
// To store the maximum sum
// for a sub-array
var _max;
// To store the maximum prefix
// sum for a sub-array
var _pre;
// To store the maximum suffix
// sum for a sub-array
var _suf;
// To store the total sum
// for a sub-array
var _sum;
}
};
// Function to create a node
function getNode(x){
var a = new Node();
a._max = x;
a._pre = x;
a._suf = x;
a._sum = x;
return a;
}
// Function to merge the 2 nodes left and right
function merg(l, r){
// Creating node ans
var ans = new Node();
// Initializing all the variables:
ans._max = ans._pre = ans._suf = ans._sum = 0;
// The max prefix sum of ans Node is maximum of
// a) max prefix sum of left Node
// b) sum of left Node + max prefix sum of right Node
// c) sum of left Node + sum of right Node
ans._pre = Math.max(l._pre, l._sum+r._pre, l._sum+r._sum);
// The max suffix sum of ans Node is maximum of
// a) max suffix sum of right Node
// b) sum of right Node + max suffix sum of left Node
// c) sum of left Node + sum of right Node
ans._suf = Math.max(r._suf, r._sum+l._suf, l._sum+r._sum);
// Total sum of ans Node = total sum of left Node + total sum of right Node
ans._sum = l._sum + r._sum;
// The max sum of ans Node stores the answer which is the maximum value among:
// prefix sum of ans Node
// suffix sum of ans Node
// maximum value of left Node
// maximum value of right Node
// prefix value of right Node + suffix value of left Node
ans._max = Math.max(ans._pre, ans._suf, ans._sum,l._max, r._max, l._suf+r._pre);
// Return the ans Node
return ans;
}
// Function for calculating the
// max_sum_subArray using divide and conquer
function getMaxSumSubArray(l, r, ar){
if (l == r) return getNode(ar[l]);
var mid = (l + r) >> 1;
// Call method to return left Node:
var left = getMaxSumSubArray(l, mid, ar);
// Call method to return right Node:
var right = getMaxSumSubArray(mid+1, r, ar);
// Return the merged Node:
return merg(left, right);
}
// Driver code
var ar = [-2, -5, 6, -2, -3, 1, 5, -6];
var n = ar.length;
var ans = getMaxSumSubArray(0, n-1, ar);
document.write("Answer is " + ans._max + "<br>");
// This code is contributed by rutvik_56.
</script>
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).
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem