# Maximum Subarray OR Largest Sum Contiguous Subarray Problem – Divide and Conquer

Objec­tive:  The max­i­mum sub­ar­ray prob­lem is the task of find­ing the con­tigu­ous sub­ar­ray within a one-dimensional array of num­bers which has the largest sum.

Exam­ple:

```int [] A = {−2, 1, −3, 4, −1, 2, 1, −5, 4};
Output: contiguous subarray with the largest sum is 4, −1, 2, 1, with sum 6.
```

Approach:

Ear­lier we have seen how to solve this prob­lem using Kadane’s Algo­rithm and using Dynamic pro­gram­ming. In this article we will solve the problem using divide and conquer.

1.     Task is to find out subarray which has the largest sum. So we need to find out the 2 indexes (left index and right index) between which the sum is maximum.

2.     Divide the problem into 2 parts, left half and right half.

1. Now we can conclude the final result will be in one of the three possibilities.
1. Left half of the array. (Left index and right index both are in left half of the array).
2. Right half of the array. (Left index and right index both are in right half of the array).
3. Result will cross the middle of the array. (Left index in the and left half of the array and right index in right half of the array).
2. Solve the all three and return the maximum among them.
3. Left half and right half of the array will be solved recursively.

Complete Code:

 public class MaximumSubArray { public int maxSubArray(int [] A){ if(A.length==0)//if length = 0, return 0 return 0; else return maxSubArray(A, 0, A.length–1); } public int maxSubArray(int [] A, int start, int end){ if(start==end){ return A[start]; //if only one element, return that } int mid = start + (end–start)/2; int leftMaxSum = maxSubArray(A, start, mid); int rightMaxSum = maxSubArray(A, mid+1, end); //lets calculate the part in which sub array will start in the left half and ends in right half int sum = 0; int leftMidMax =0; for (int i = mid; i >=start ; i—) { sum += A[i]; if(sum>leftMidMax) leftMidMax = sum; } sum = 0; int rightMidMax =0; for (int i = mid+1; i <=end ; i++) { sum += A[i]; if(sum>rightMidMax) rightMidMax = sum; } int centerSum = leftMidMax + rightMidMax; return Math.max(centerSum, Math.max(leftMaxSum, rightMaxSum)); } public static void main(String[] args) { int [] A = {–2, 12, –5, 10, –1, –6, 4}; MaximumSubArray m = new MaximumSubArray(); System.out.println("Maximum Sub Array sum is : " + m.maxSubArray(A)); } }

view raw
MaximumSubArray.java
hosted with ❤ by GitHub

Output:

```Maximum Sub Array sum is : 17
```