Maximum Subarray

Medium

Topics
ArrayDynamic Programming

Given an integer array nums, find the contiguous subarray with the largest sum and return its sum.

Example 1

-2011-3243-142516-5748sum = 6
The braced run is the contiguous block with the largest sum, 6. The one-pass rule is the whole idea: a running sum that has gone negative can never help what comes next, so drop it and start again at the current element.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has sum 6.

Example 2

5041-127384sum = 23
Input:  nums = [5,4,-1,7,8]
Output: 23

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

Consider the best subarray that ends at each index. When you extend to a new element, you either continue the previous subarray or start fresh at the new element.

The decision is simple: if the running sum has dropped below zero, it can only hurt what follows, so discard it and restart. This is Kadane’s algorithm.

Approach

  1. Keep cur = best sum of a subarray ending here, and best = best anywhere.
  2. For each element: cur = max(x, cur + x) (restart vs. extend).
  3. Update best = max(best, cur).
  4. Return best.

Walkthrough

nums = [-2, 1, -3, 4, -1, 2, 1]

x=-2  cur=-2  best=-2
x= 1  cur=1    best=1
x=-3  cur=-2   best=1
x= 4  cur=4    best=4
x=-1  cur=3    best=4
x= 2  cur=5    best=5
x= 1  cur=6    best=6  -> answer 6

Complexity

  • Time — O(n): one pass, constant work per element.
  • Space — O(1): two running scalars.

Common Pitfalls

  • Initialize with nums[0], not 0 — an all-negative array must still return its largest single element.

Full Solution — all languages

class Solution:
    def maxSubArray(self, nums):
        best = nums[0]
        running = nums[0]
        # range, not nums[1:]: the slice would copy n-1 elements and quietly make
        # this O(n) auxiliary space, which is the one property Kadane's is known for.
        for i in range(1, len(nums)):
            v = nums[i]
            running = max(v, running + v)
            best = max(best, running)
        return best
SensAI
Beta
Tap the mic to stop voice mode