← DSA
MEDIUM

Maximum Subarray

PracticeNeetCode ↗LeetCode ↗

Given an integer array nums, find the contiguous subarray (with at least one number) that has the largest sum, and return that sum.

Example

Input nums = [-2,1,-3,4,-1,2,1,-5,4]
Output 6

Key Pointers

Step-by-Step Analysis

  1. Initialize curSum and maxSum both to nums[0].
  2. For each subsequent number n: curSum = max(n, curSum + n) — either extend the running subarray or start fresh at n.
  3. Update maxSum = max(maxSum, curSum) after each step.
  4. Return maxSum once the array is exhausted.

Complexity

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

Code

def maxSubArray(nums: list[int]) -> int:
    curSum = maxSum = nums[0]
    for n in nums[1:]:
        curSum = max(n, curSum + n)
        maxSum = max(maxSum, curSum)
    return maxSum

Code Explanation

How the solution above works, piece by piece.

  1. curSum = the best sum of a subarray that ends exactly at the current element.
  2. curSum = max(n, curSum + n): either extend the previous subarray or start fresh at n. Starting fresh wins exactly when the running sum has gone negative, since a negative prefix only drags the total down.
  3. maxSum keeps the best curSum seen anywhere.
  4. Starting from nums[0] (not 0) makes an all-negative array return its largest element.
  5. This is Kadane's algorithm: one pass, O(n) time, O(1) space.

Visual Walkthrough

Running it on nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]:

trace-2011-3243-142516-5748i=0cur -2, best -2-21-34-121-54i=1restart; cur 1, best 1-21-34-121-54i=2extend; cur -2, best 1-21-34-121-54i=3restart; cur 4, best 4-21-34-121-54i=4extend; cur 3, best 4-21-34-121-54i=5extend; cur 5, best 5-21-34-121-54i=6extend; cur 6, best 6-21-34-121-54i=7extend; cur 1, best 6-21-34-121-54i=8extend; cur 5, best 6-21-34-121-54best[4, −1, 2, 1] = 6
Blue is the subarray curSum currently describes. It restarts at 1 and at 4 because the sum so far was negative. The best window is [4, −1, 2, 1] = 6.
current windowcurrent element

Video Explanation

NeetCode — Amazon Interview Question, LeetCode 53