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^4See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI