Maximum Subarray Sum Problem
The Maximum Subarray Sum problem asks: given an array of integers (which may include negative numbers), find the contiguous subarray with the largest sum, and return that sum.
Brute Force Approach
Check every possible subarray and compute its sum, keeping track of the maximum found. This takes O(n²) time, which is too slow for large arrays.
Kadane's Algorithm (Optimal Approach)
Kadane's Algorithm solves this in a single pass by keeping a running sum. At each element, decide whether to extend the existing subarray or start a new one from the current element.
def max_subarray_sum(nums):
current_sum = max_sum = nums[0]
for num in nums[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
print(max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # Output: 6
Complexity
| Approach | Time | Space |
|---|---|---|
| Brute Force | O(n²) | O(1) |
| Kadane's Algorithm | O(n) | O(1) |
Applications
- Stock price analysis — best time period for maximum profit trends.
- Signal processing to find the strongest continuous segment.
- A common building block for more advanced DP problems.
Tracing Kadane's Algorithm Step by Step
Here is what the two running values look like on [-2, 1, -3, 4, -1, 2, 1, -5, 4]. At every step, current_sum is the best sum of a subarray that must end at this element.
| Index | num | current_sum | max_sum | Decision |
|---|---|---|---|---|
| 0 | -2 | -2 | -2 | Start |
| 1 | 1 | 1 | 1 | Restart: 1 beats -2 + 1 |
| 2 | -3 | -2 | 1 | Extend |
| 3 | 4 | 4 | 4 | Restart: 4 beats -2 + 4 |
| 4 | -1 | 3 | 4 | Extend |
| 5 | 2 | 5 | 5 | Extend |
| 6 | 1 | 6 | 6 | Extend |
| 7 | -5 | 1 | 6 | Extend |
| 8 | 4 | 5 | 6 | Extend |
The winning subarray is [4, -1, 2, 1] from index 3 to 6. The key insight: whenever the running sum becomes worse than the current element alone, carrying the past along only hurts, so you start fresh.
Returning the Subarray, Not Just the Sum
Interviewers often ask for the start and end positions too. Track where the current run began and save it whenever a new best appears.
def max_subarray_with_indices(nums):
best_sum = cur_sum = nums[0]
start = best_start = best_end = 0
for i in range(1, len(nums)):
if nums[i] > cur_sum + nums[i]:
cur_sum = nums[i]
start = i # begin a new run here
else:
cur_sum += nums[i]
if cur_sum > best_sum:
best_sum = cur_sum
best_start, best_end = start, i
return best_sum, best_start, best_end
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
total, s, e = max_subarray_with_indices(nums)
print(total, nums[s:e + 1]) # 6 [4, -1, 2, 1]
Edge Cases and Common Bugs
- All negative numbers. For
[-3, -1, -2]the answer is -1. If you startmax_sumat 0, you wrongly return 0, which corresponds to an empty subarray most problems do not allow. - Empty input. Decide in advance whether to raise an error or return 0, and handle it before reading
nums[0]. - Single element. The answer is that element; make sure the loop does not break when there is nothing after index 0.
- Integer overflow in languages like Java or C++. For large values, use
longfor the running sums. - Confusing subarray with subsequence. A subarray must be contiguous. If gaps were allowed, you would simply add all positive numbers.
Related Variations to Practise Next
- Maximum circular subarray: the answer is the larger of normal Kadane and the total sum minus the minimum subarray sum, unless every number is negative.
- Maximum product subarray: track both the largest and smallest product, because a negative number can flip the smallest into the largest.
- Divide and conquer version: split the array, solve each half, and check the best sum crossing the middle. It runs in O(n log n) and is a good exercise in recursion.
- 2D maximum sum rectangle: fix a pair of rows, compress the columns into one array, and apply Kadane to it.
Interview tip: explain the brute force first, then describe Kadane as dynamic programming where each state is "best sum ending here". That framing shows you understand why it works.