![]() |
VOOZH | about |
Given an array arr[], the task is to find the subarray that has the maximum sum and return its sum.
Examples:
Input: arr[] = [2, 3, -8, 7, -1, 2, 3]
Output: 11
Explanation: The subarray [7, -1, 2, 3] has the largest sum 11.Input: arr[] = [-2, -4]
Output: –2
Explanation: The subarray [-2] has the largest sum -2.Input: arr[] = [5, 4, 1, 7, 8]
Output: 25
Explanation: The subarray [5, 4, 1, 7, 8] has the largest sum 25.
Table of Content
The idea is to run two nested loops to iterate over all possible subarrays and find the maximum sum. The outer loop will mark the starting point of a subarray and inner loop will mark the ending point of the subarray. Please refer to Maximum Subarray Sum for implementation.
Divide the given array in two halves and return the maximum of following three:
Maximum subarray in left and right half can be found easily by two recursive calls. To find maximum subarray sum such that the subarray crosses the midpoint, find the maximum sum starting from mid point and ending at some point on left of mid, then find the maximum sum starting from mid + 1 and ending with some point on right of mid + 1. Finally, combine the two and return the maximum among left, right and combination of both.
Below is the implementation of the above approach:
21
Note: The above recurrence is similar to Merge Sort and can be solved either using Recurrence Tree method or Master method.
The Kadane's Algorithm for this problem takes O(n) time. Therefore the Kadane's algorithm is better than the Divide and Conquer approach, but this problem can be considered as a good example to show power of Divide and Conquer. The above simple approach where we divide the array in two halves, reduces the time complexity from O(n^2) to O(nLogn). Please refre to kadane's algorithm implementation Maximum Subarray Sum.