← Back to Algorithms, page 1

algorithms-0008 · Medium fresher

Maximum subarray sum (Kadane's algorithm): find the contiguous subarray with the largest sum and return the sum and its position.

Scan left to right, keeping the best sum of a subarray that ends at the current index. If that running sum is negative, start fresh at the current element, because a negative prefix can only lower any future sum. Track the best value seen. This is O(n) time and O(1) space, versus O(n^2) for checking all subarrays.

Full answer

Problem

Given a non-empty list nums, return (best_sum, start, end) for the contiguous subarray nums[start:end + 1] with the largest sum.

Example: [-2, 1, -3, 4, -1, 2, 1, -5, 4] gives (6, 3, 6), the subarray [4, -1, 2, 1].

Constraints: 1 <= len(nums) <= 10^5, values from -10^4 to 10^4. The subarray must be non-empty, so for all-negative input the answer is the largest single element.

Brute force

Try every start and end: O(n^2) with a running sum (O(n^3) if each sum is recomputed).

Optimal approach

Keep cur, the best sum of a subarray ending at index i:

  • If cur < 0, a subarray ending at i is better off starting at i: cur = nums[i], remember start = i.
  • Otherwise extend it: cur += nums[i].
  • If cur > best, record best and its boundaries.

Think of a cricket batter's run differences over overs: once the running total since you started counting is negative, you drop that stretch and start counting again from the next over.

Why it works

Let cur(i) be the maximum sum of a subarray ending exactly at i. Either that subarray is just nums[i], or it extends the best subarray ending at i - 1. So cur(i) = nums[i] + max(cur(i - 1), 0). The overall answer is the maximum of cur(i) over all i. Kadane's algorithm is this one-dimensional dynamic programme with the table reduced to one variable.

Complexity

O(n) time, O(1) space.

Code

python
def max_subarray(nums):
    """Kadane's algorithm: largest sum of a non-empty contiguous subarray.

    Returns (best_sum, start, end) with end inclusive.
    """
    if not nums:
        raise ValueError("nums must be non-empty")
    best = cur = nums[0]
    start = best_start = best_end = 0
    for i in range(1, len(nums)):
        if cur < 0:                 # a negative prefix only hurts; restart here
            cur = nums[i]
            start = i
        else:
            cur += nums[i]
        if cur > best:
            best, best_start, best_end = cur, start, i
    return best, best_start, best_end


def max_subarray_brute(nums):
    return max(sum(nums[i:j + 1]) for i in range(len(nums)) for j in range(i, len(nums)))


if __name__ == "__main__":
    assert max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == (6, 3, 6)
    assert max_subarray([5]) == (5, 0, 0)
    assert max_subarray([-3, -1, -2]) == (-1, 1, 1)     # all negative
    assert max_subarray([2, 3, -10, 4]) == (5, 0, 1)
    assert max_subarray_brute([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
    try:
        max_subarray([])
        raise AssertionError("expected ValueError")
    except ValueError:
        pass
    print("all tests passed")

Save as a08_kadane.py and run python3 a08_kadane.py. It prints all tests passed (Python 3.13.5).

Edge cases

All negative values (answer is the largest single value; initialising best = 0 would be wrong). A single element. Empty input is invalid here and raises ValueError. Several subarrays with the same best sum: this version returns the first one found.

Pattern

Running state with reset, a compressed DP over "best ending here". Variants include maximum product subarray (track both max and min), circular maximum subarray (total minus minimum subarray) and the maximum sum rectangle in a matrix.

python
def max_subarray(nums):
    """Kadane's algorithm: largest sum of a non-empty contiguous subarray.

    Returns (best_sum, start, end) with end inclusive.
    """
    if not nums:
        raise ValueError("nums must be non-empty")
    best = cur = nums[0]
    start = best_start = best_end = 0
    for i in range(1, len(nums)):
        if cur < 0:                 # a negative prefix only hurts; restart here
            cur = nums[i]
            start = i
        else:
            cur += nums[i]
        if cur > best:
            best, best_start, best_end = cur, start, i
    return best, best_start, best_end


def max_subarray_brute(nums):
    return max(sum(nums[i:j + 1]) for i in range(len(nums)) for j in range(i, len(nums)))


if __name__ == "__main__":
    assert max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == (6, 3, 6)
    assert max_subarray([5]) == (5, 0, 0)
    assert max_subarray([-3, -1, -2]) == (-1, 1, 1)     # all negative
    assert max_subarray([2, 3, -10, 4]) == (5, 0, 1)
    assert max_subarray_brute([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
    try:
        max_subarray([])
        raise AssertionError("expected ValueError")
    except ValueError:
        pass
    print("all tests passed")

Returns the sum and the inclusive start and end indices; includes an O(n^2) brute force used in the tests.

Complexity

Time: O(n). Space: O(1). The brute-force reference in the file is O(n^2) time.

By level

Fresher: Writes Kadane's loop, explains the reset rule with an example and tests an all-negative list. Should be able to trace the running sum on a short example.

Mid: Derives the recurrence, returns boundaries and relates it to dynamic programming. Returns the start and end indices of the best subarray.

Senior: Extends to circular and 2D versions, product variants, and discusses divide-and-conquer or segment-tree versions that support updates. Can phrase the method as a one-dimensional dynamic programming recurrence.

Key points

  • cur(i) = nums[i] + max(cur(i - 1), 0)
  • Reset when the running sum becomes negative
  • Track the best sum and its boundaries separately
  • All-negative input returns the largest element
  • It is a DP with O(1) state

Common mistakes

  • Initialising best to 0 and failing on all-negative input
  • Resetting when cur is zero versus negative without thinking about ties
  • Losing track of the start index when resetting
  • Allowing an empty subarray when the problem forbids it

Follow-ups

  • How do you solve maximum product subarray?
  • How does the circular version work?
  • How would you find the maximum sum rectangle in a 2D grid?

Tips

  • Write the recurrence before the code
  • Test with an all-negative list
  • Explain why a negative prefix is never useful

Evaluation rubric

  • Correct O(n) algorithm
  • Correct handling of all-negative input
  • Explains the recurrence or reset argument
  • Returns indices correctly if asked