Common patterns · Medium

Maximum subarray

Return the largest sum of a nonempty contiguous subarray. Input is nonempty. Choose one nonempty run of consecutive values. A negative running total can make a fresh start better.

Worked example

[-2, 1, -3, 4, -1, 2, 1, -5, 4] → 6

  1. Start a new run at 4 rather than carrying the earlier negative sum.
  2. Extend through -1, 2, and 1. The run [4, -1, 2, 1] sums to 6, the maximum.

Python solution

def solve(nums):
    current = best = nums[0]
    for index in range(1, len(nums)):
        current = max(nums[index], current + nums[index])
        best = max(best, current)
    return best

At each position, extend the previous subarray or start a new one.

Time: O(n) · Space: O(1)

Practise in GymType