Objective: The maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers which has the largest sum.

Example:

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:

Earlier we have seen how to solve this problem using Kadane’s Algorithm and using Dynamic programming. 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.

Now we can conclude the final result will be in one of the three possibilities.

Left half of the array. (Left index and right index both are in left half of the array).

Right half of the array. (Left index and right index both are in right half of the array).

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).

Solve the all three and return the maximum among them.

Left half and right half of the array will be solved recursively.

Complete Code:

Output:

Maximum Sub Array sum is : 17

__________________________________________________ Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________