Maximum Subarray
2 approaches, code in every language
Problem description
Given an integer array nums, find a contiguous run of one or more elements whose total is as large as possible, and return that maximum total. The chosen slice must be a single unbroken window of the array.
The values may be negative, so the answer is not always the sum of everything; sometimes a single element is the best you can do. Solve it here with a divide-and-conquer strategy that considers the best window fully inside the left half, fully inside the right half, and one that straddles the midpoint.
Example 1
Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6
The window [4, -1, 2, 1] sums to 6, the largest achievable total.
Example 2
Input: nums = [-3, -1, -2]
Output: -1
Every value is negative, so the best window is the single element -1.
Constraints
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Best Trading Day Run is our own problem on the technique behind Maximum Subarray: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free