MediumArrays · Dynamic Programming · Divide and Conquer

Maximum Subarray

Given an integer array nums, find the contiguous, non-empty subarray with the largest sum and return that sum.

nums = [2,−3,4,−2,2,1,−1,4] → 8 ([4,−2,2,1,−1,4])nums = [−1] → −1

Try:
CALL
1 / 1

Code

The highlighted line runs next. The pill shows the live values in the running call.

Variables

The data structures the code is building

The array

Brackets below = subarrays being tracked; gold above = best so far

Time and space complexity

n = len(nums). The highlighted row is the solution being traced.

Keyboard: ← → step, Space play or pause. Integers from −99 to 99; drawings use at most 10 numbers for brute force, 12 for divide and conquer and 16 for Kadane.