numbers = [-2, 1, -3, 4, -1, 2, 1, -5, 4]→ 6The contiguous segment [4, -1, 2, 1] sums to 6.
Given a non-empty integer array, return the largest sum of any non-empty contiguous subarray. The chosen segment may contain one element or the entire array.
numbers = [-2, 1, -3, 4, -1, 2, 1, -5, 4]→ 6The contiguous segment [4, -1, 2, 1] sums to 6.
numbers = [-5, -2, -8]→ -2The single value -2 is better than every other non-empty segment.
numbers = [4, -1, 2]→ 5Keeping the small negative bridge connects 4 and 2 into a better segment.
Try every start index, extend an end index while maintaining its running sum, and keep the largest value. This inspects O(n²) contiguous segments and uses O(1) extra space.
Scan left to right. Let ending be the best non-empty segment that must end at the current position. Either start anew with the current value or extend the best segment ending one position earlier. Update a global best after each choice.
After index i, ending is the maximum sum among non-empty subarrays ending exactly at i. Every such subarray is either the single value at i or extends a subarray ending at i−1, so max(value, previousEnding + value) is complete.
The scan visits every value once and stores only ending and best, so it takes O(n) time and O(1) extra space. The nested-start baseline takes O(n²) time.
For [-5, -2, -8], initializing best to zero incorrectly chooses an empty segment. The problem requires a non-empty answer, so initialize from the first value.
Each frame shows the current value, the previous ending sum, whether the scan restarts or extends, and the best result found anywhere so far.
Index 0, value -2. Best ending here: -2; best anywhere: -2.
The first value is the only non-empty subarray ending here.Without looking back at the explanation, name the signal, the state you keep, one safe transition, the cost, and a case that breaks a tempting mistake. This writing is private and not automatically graded.
Write solve(data). data.numbers is a non-empty integer array. Return the maximum sum of a contiguous non-empty segment. Checks include mixed, all-negative, single-value, and fresh arrays.
Opening the code studio…
Loading your saved attempts…
This lesson uses original explanations and examples. For additional practice, see the related LeetCode challenge.