DSA Visualizer · 25 visualizationsMaximum Subarray
MediumDynamic Programming

Maximum Subarray

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

nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]Step 1 of 9
-2
0l, i
1
1
-3
2
4
3
-1
4
2
5
1
6
-5
7
4
8
current sum / best
cur -2
best -2

Start with just the first value -2. The running sum and the best sum both begin at -2.

Pythontime O(n) · space O(1)
1def maxSubArray(nums):
2 cur = nums[0]
3 best = nums[0]
4 for i in range(1, len(nums)):
5 cur = max(nums[i], cur + nums[i])
6 best = max(best, cur)
7 return best
Variables
i—
num—
cur-2
best-2

Problem

Given an integer array nums, find the subarray with the largest sum, and return its sum. Kadane's Algorithm: At each position, decide whether to extend the current subarray or start fresh. If the current sum becomes negative, reset it — a negative prefix only hurts us.

Examples

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

[4,-1,2,1] has the largest sum = 6

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

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴

Intuition

Either the best subarray ending at the previous position is worth extending, or it is not. If the running sum would make the new element smaller, start a fresh subarray here; otherwise keep extending. Track the best sum seen along the way.

Brute force → Optimal

Brute force

Consider every start and end index and sum the subarray with a running total.

Time O(n²)Space O(1)
Optimal

Kadane's algorithm: one pass where each step chooses to extend or restart and updates the best sum.

Time O(n)Space O(1)

Complexity

Time O(n)Space O(1)

Edge cases

  • All values negative, e.g. [-3,-1,-4,-2]: the answer is the single largest element, -1.
  • A single element: it is the only subarray, so return that element.

Common mistakes

  • Initialising best to 0, which is wrong for an all-negative array where the true answer is negative.
  • Forgetting to restart the running sum when extending would only make the next element smaller.
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free