This post is completed by 1 user
|
Add to List |
222. 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 the 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, the left half and the right half.
- Now we can conclude the final result will be in one of the three possibilities.
- The left half of the array. (Left index and right index both are in the left half of the array).
- The right half of the array. (Left index and right index both are in the right half of the array).
- The result will cross the middle of the array. (Left index in the left half of the array and right index in the right half of the array).
- Solve all three and return the maximum among them.
- The left half and right half of the array will be solved recursively.
Output:
Maximum Sub Array sum is : 17