Algorithms · Visualized
Maximum Subarray (D&C)
Divide & Conquer
Break a problem into independent subproblems, solve each, and combine the answers.
Finds the contiguous subarray with the largest sum by splitting the array in half. Time: O(n log n) average, O(n log n) — note Kadane's algorithm solves this in O(n), but D&C is a classic teaching approach worst; space: O(log n) — recursion stack.
Big-O: Classic D&C recursions: Merge Sort, Quick Sort, Maximum Subarray, Fast Power.
Maximum Subarray (Divide & Conquer)
Divide & ConquerFinds the contiguous subarray with the largest sum by splitting the array in half. The best subarray either lies entirely in the left half, entirely in the right half, or crosses the middle — so the algorithm computes all three possibilities and takes the best.
How Maximum Subarray (D&C) Works
- Base case: if the array has one element, that element itself is the maximum subarray sum.
- Split the array into a left half and a right half at the midpoint.
- Recursively find the maximum subarray sum entirely within the left half.
- Recursively find the maximum subarray sum entirely within the right half.
- Compute the maximum sum of a subarray that crosses the midpoint, by extending outward from the middle in both directions.
- Return the largest of the three: left max, right max, and cross-the-middle max.
Maximum Subarray (D&C) Worked Example
Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Split around the middle. Left half best might be [4,-1,2,1]=6 (crossing within left-right sub-split). Right half best might just be [4]=4. Crossing sum around the true midpoint checks combinations like [4,-1,2,1]=6 too. Comparing all candidates, the overall best is [4,-1,2,1] with sum 6.
def max_subarray(a, lo, hi):
if lo == hi:
return a[lo]
mid = (lo + hi) // 2
left = max_subarray(a, lo, mid)
right = max_subarray(a, mid + 1, hi)
s = best = a[mid]
for i in range(mid - 1, lo - 1, -1):
s += a[i]
best = max(best, s)
s2 = best2 = a[mid + 1]
for i in range(mid + 2, hi + 1):
s2 += a[i]
best2 = max(best2, s2)
return max(left, right, best + best2)Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Maximum Subarray (D&C) Time & Space Complexity
When to Use Maximum Subarray (D&C)
- Teaching the divide-and-conquer pattern on a problem that also has a simpler linear solution (Kadane's), for comparison.
- The 'combine across the split point' technique reappears in Closest Pair of Points and Count Inversions.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.