Sub topic 11
Maximum Subarray: Handling the Crossing Case
This chapter assumes you can trace recursive functions, read Big-O notation, and solve recurrences such as T(n) = 2T(n/2) + O(n), as covered in the earlier chapters on recurrences and merge sort.
The Problem
Given a list of numbers, some of them negative, find the largest sum of a non-empty contiguous slice. For [-2, 1, -3, 4, -1, 2, 1, -5, 4] the answer is 6, from the slice [4, -1, 2, 1].
The brute-force approach checks every pair of start and end positions, which takes O(n²) time. Divide and conquer brings this down to O(n log n).
Three Places the Answer Can Be
Split the range at the midpoint. The best slice must fall into exactly one of three cases:
- It lies entirely in the left half.
- It lies entirely in the right half.
- It crosses the midpoint, so it includes both
a[mid - 1]anda[mid].
Recursion handles the first two cases. The third case is new: no recursive call can find it, because each call sees only one half of the range.
Computing the Crossing Case
A crossing slice has two parts: a suffix of the left half that ends at mid - 1, and a prefix of the right half that starts at mid. The two parts are independent, so you maximize each one separately. Scan leftward from mid - 1 and record the best running sum. Then scan rightward from mid and do the same. The best crossing sum is the two results added together.
def max_subarray(a, lo, hi):
# Maximum sum of a non-empty contiguous slice of a[lo:hi]
if hi - lo == 1:
return a[lo]
mid = (lo + hi) // 2
best_left = max_subarray(a, lo, mid)
best_right = max_subarray(a, mid, hi)
s, left_cross = 0, float('-inf')
for i in range(mid - 1, lo - 1, -1):
s += a[i]
left_cross = max(left_cross, s)
s, right_cross = 0, float('-inf')
for i in range(mid, hi):
s += a[i]
right_cross = max(right_cross, s)
return max(best_left, best_right, left_cross + right_cross)
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(max_subarray(nums, 0, len(nums))) # 6Both scans start from negative infinity rather than 0. Each side therefore has to contribute at least one element, and a list of all negative numbers returns its largest element instead of 0.
Running Time
There are two half-size recursive calls, and the crossing scans touch every element of the range once:
T(n) = 2T(n/2) + O(n) = O(n log n)
This is the same recurrence as merge sort and falls under case 2 of the master theorem.
Common Errors
| Mistake | Effect |
|---|---|
| Combining `best_left + best_right` as the crossing case | Those two slices may not touch the midpoint, so the "slice" they form isn't contiguous |
| Starting the cross sums at 0 | All-negative input returns 0, which is the sum of an empty slice |
| Base case `hi - lo == 0` only | An empty range has no valid answer, and size-1 ranges never stop the recursion |
Exercise
What does max_subarray([-3, -1, -2], 0, 3) return, and which of the three cases produces it at the top level?
Show answer
It returns -1. At the top level mid = 1. The left half [-3] gives -3. The right half [-1, -2] gives -1. The crossing sum is -3 + (-1) = -4. The maximum, -1, comes from the right-half case.
Exercise
Why does the crossing case need only O(n) time instead of trying every pair of start and end points?
Show answer
A crossing slice is a left suffix ending at mid - 1 joined to a right prefix starting at mid. The two parts don't depend on each other, so you maximize each with its own linear scan and add the two results. You never need to try them in pairs.