Largest Sum Contiguous Subarray (Kadane’s Algorithm) medium

Description

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

A subarray is a contiguous non-empty sequence of elements within the array.

Examples

> Case 1:
    Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
    Output: 6
    Explanation: The subarray [4, -1, 2, 1] has the largest sum = 6.
 
> Case 2:
    Input: nums = [1]
    Output: 1
 
> Case 3:
    Input: nums = [5, 4, -1, 7, 8]
    Output: 23
    Explanation: The entire array [5, 4, -1, 7, 8] has the largest sum = 23.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

The Brute Force (Don’t Do This)

Checking all possible subarrays takes O(n^2) or O(n^3). Kadane’s algorithm solves it in O(n).

Kadane’s Algorithm

The core idea: at each position, decide whether to extend the current subarray or start a new one. If the running sum becomes negative, it’s better to start fresh.

Kadane's Algorithm: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Step 1 of 9
-2
[0]
1
[1]
-3
[2]
4
[3]
-1
[4]
2
[5]
1
[6]
-5
[7]
4
[8]
i=0: currentSum = max(-2, -2) = -2. maxSum = -2.

Code

Explanation

The algorithm maintains two variables:

  • currentSum: the maximum sum of a subarray ending at the current position
  • maxSum: the overall maximum sum seen so far

At each element, we make a simple choice:

  1. Extend the existing subarray: currentSum + nums[i]
  2. Start fresh from this element: nums[i]

We pick whichever is larger. If currentSum has gone negative, the current element alone is better than dragging along a negative prefix.

Why Kadane’s works: A negative prefix can never improve a subarray sum. If currentSum drops below 0, any future subarray is better off starting from scratch. This greedy insight makes the single-pass O(n) solution possible.

Analysis

  • Time Complexity: O(n) — single pass through the array
  • Space Complexity: O(1) — only two extra variables