Sub topic 11
Maximum Subarray: Handling the Crossing Case
This chapter assumes you can trace recursive Python functions, read Big-O notation, and apply the master theorem from the earlier chapter. It also helps to remember how merge sort splits a list at its midpoint, because the maximum subarray algorithm splits a list the same way.
The Problem
You are given a list of numbers, some of them negative. Find the largest sum of any contiguous slice, meaning a run of neighboring elements with nothing skipped. The slice must contain at least one element.
For [-2, 1, -3, 4, -1, 2, 1, -5, 4], the answer is 6, from the slice [4, -1, 2, 1].
A brute-force solution tries every pair of start and end positions. That costs O(n²) even if you keep running sums, and O(n³) if you recompute each sum. Divide and conquer gets the cost down to O(n log n). It also shows a pattern that recurs throughout algorithm design: the answer to the whole problem may not belong to either half.
Three Places the Answer Can Live
Split the range a[lo:hi] at mid = (lo + hi) // 2. The best slice is in exactly one of these places:
- It lies entirely in the left half,
a[lo:mid]. - It lies entirely in the right half,
a[mid:hi]. - It crosses the midpoint: it starts at some index
i < midand ends at some indexj >= mid.
The first two cases are smaller copies of the original problem, so recursion solves them. The third case is where merge sort's analogy breaks down. No recursive call can see a slice that spans both halves, so the combine step has to compute it directly.
Why the Crossing Case Is Linear
A crossing slice a[i:j+1] with i < mid <= j breaks into two pieces:
- a suffix of the left half,
a[i:mid], which always includesa[mid-1] - a prefix of the right half,
a[mid:j+1], which always includesa[mid]
The two pieces are independent. The choice of i does not limit the choice of j. So you maximize each piece separately and add the results. Scanning left from mid - 1 and keeping a running sum finds the best suffix in one pass. Scanning right from mid finds the best prefix the same way. Together the scans take O(hi − lo) time.
The Implementation
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))) # 6The function passes index bounds instead of slicing the list. Slicing would copy each half at every level. That copying is still O(n) per level and would not change the asymptotic cost, but it wastes memory and time for no benefit.
Tracing the Top Call
For nums, the top call has lo = 0, hi = 9, and mid = 4.
| Piece | Range | Result |
|---|---|---|
| Left recursion | `[-2, 1, -3, 4]` | 4 |
| Right recursion | `[-1, 2, 1, -5, 4]` | 4 |
| Best left suffix | scanning 4, -3, 1, -2 | 4 (just `[4]`) |
| Best right prefix | scanning -1, 2, 1, -5, 4 | 2 (`[-1, 2, 1]`) |
| Crossing total | 4 + 2 | 6 |
Neither half reaches 6 alone. Only the crossing case finds the answer, which is why the combine step cannot be skipped.
Running Time
Each call makes two half-size recursive calls and does linear work in the crossing scan:
T(n) = 2T(n/2) + Θ(n)
This is the same recurrence as merge sort. With a = 2, b = 2, and f(n) = Θ(n) = Θ(n^(log₂ 2)), master theorem case 2 gives Θ(n log n). The recursion depth is about log₂ n, so the stack stays shallow even for large inputs.
Recovering the Slice Itself
Usually you want to know where the slice is, not only its sum. The version below returns (sum, start, end) with end exclusive.
def max_subarray_idx(a, lo, hi):
# Returns (best_sum, start, end) for a[lo:hi]; the slice is a[start:end]
if hi - lo == 1:
return a[lo], lo, hi
mid = (lo + hi) // 2
left = max_subarray_idx(a, lo, mid)
right = max_subarray_idx(a, mid, hi)
s, best_l, best_i = 0, float('-inf'), mid
for i in range(mid - 1, lo - 1, -1):
s += a[i]
if s > best_l:
best_l, best_i = s, i
s, best_r, best_j = 0, float('-inf'), mid
for j in range(mid, hi):
s += a[j]
if s > best_r:
best_r, best_j = s, j + 1
cross = (best_l + best_r, best_i, best_j)
return max(left, right, cross, key=lambda t: t[0])
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
total, start, end = max_subarray_idx(nums, 0, len(nums))
print(total, nums[start:end]) # 6 [4, -1, 2, 1]When sums tie, max with key returns the first maximum it sees. That means ties go to the left half, then the right half, then the crossing slice. If your application needs a specific tie rule, such as the shortest slice, state it and encode it in the key.
Common Errors
Other mistakes to watch for:
- Off-by-one in the left scan. The loop is
range(mid - 1, lo - 1, -1). Writingrange(mid, lo, -1)includesa[mid]on the wrong side and skipsa[lo]. - Missing empty-input guard. If you call the function with
hi == lo, thenmid == lo, and the left call repeats the same empty range until Python raisesRecursionError. Check for an empty list before the first call. - Treating the crossing case as optional. Some people assume the best slice always sits inside one half. The trace above shows a case where it does not.
Testing Against Brute Force
A small randomized test catches most boundary bugs:
import random
def max_subarray(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)
def brute(a):
return max(sum(a[i:j]) for i in range(len(a)) for j in range(i + 1, len(a) + 1))
for _ in range(1000):
a = [random.randint(-10, 10) for _ in range(random.randint(1, 12))]
assert max_subarray(a, 0, len(a)) == brute(a), a
print("all tests passed")Exercises
Exercise
For the input [-3, -1, -2], what do bestleft, bestright, and the crossing total equal in the top call (lo=0, hi=3, mid=1), and what does the function return?
Show answer
bestleft is maxsubarray([-3]) = -3. bestright is maxsubarray([-1, -2]) = -1. The best left suffix is -3 (just a[0]), and the best right prefix is -1 (just a[1]), so the crossing total is -4. The function returns max(-3, -1, -4) = -1.
Exercise
Change the combine step so the whole algorithm runs in O(n). Hint: have each call return four values for its range instead of one.
Show answer
Have each call return (total, bestprefix, bestsuffix, best). For left result L and right result R, combine in O(1): total = L.total + R.total; bestprefix = max(L.bestprefix, L.total + R.bestprefix); bestsuffix = max(R.bestsuffix, R.total + L.bestsuffix); best = max(L.best, R.best, L.bestsuffix + R.bestprefix). The base case returns (x, x, x, x). The recurrence becomes T(n) = 2T(n/2) + O(1), which is O(n) by master theorem case 1.
Exercise
Why can the best left suffix and the best right prefix be chosen independently when computing the crossing case?
Show answer
Every crossing slice is a left suffix ending at a[mid-1] joined to a right prefix starting at a[mid]. Its sum is the sum of the two pieces, and picking a start index on the left places no restriction on the end index on the right. So the largest total comes from the largest suffix plus the largest prefix.