VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-subarray-sum-using-divide-and-conquer-algorithm/

⇱ Maximum Subarray Sum using Divide and Conquer algorithm - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Subarray Sum using Divide and Conquer algorithm

Last Updated : 23 Jul, 2025

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.

[Naive Approach] By iterating over all subarrays - O(n^2) Time and O(1) Space

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.

[Better Approach] Using Divide and Conquer - O(n*logn) time and O(n) space

Divide the given array in two halves and return the maximum of following three:

  1. Maximum subarray sum in left half.
  2. Maximum subarray sum in right half.
  3. Maximum subarray sum such that the subarray crosses the midpoint.

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: 


Output
21

Note: The above recurrence is similar to Merge Sort and can be solved either using Recurrence Tree method or Master method.

[Expected Approach] Using Kadane’s Algorithm - O(n) Time and O(1) Space

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.

Comment