Maximum Subarray
A subarray is a run of neighbouring elements of a list, taken without gaps. Among all the non-empty subarrays of a list of integers, you want the one whose elements add up to the most, and you return that sum.
In [2, -4, 3, -1, 5, -6, 1] the best run is [3, -1, 5], with a sum of 7. It keeps the -1 because the 5 after it more than pays for it, and it leaves out the 2 at the start because the -4 that follows costs more than the 2 brings.
The classic one pass solution is Kadane's algorithm. Walk through the list and keep the best sum of a run that ends at the current element. At each element there are only two choices: extend the run that ended at the previous element, or restart with a new run that begins here. Extending pays off only while the earlier run has a positive sum; once that sum drops to zero or below, carrying it along can only hurt, so you start fresh. The answer is the largest run sum seen anywhere along the way.
For the example, the best run sums ending at each position are 2, -2, 3, 2, 7, 1 and 2, so the answer is 7. Every element is looked at once, so the work grows linearly with the length of the list.
Write a function named maxSubArray that gets a list of integers nums and returns the largest sum of a contiguous, non-empty subarray of nums.
Constraints: 1 ≤ nums.length ≤ 10^5, -10^4 ≤ nums[i] ≤ 10^4.
Function
- arg1integer-array
- Returnsinteger
Examples
- Input
- arg1 = [2, -4, 3, -1, 5, -6, 1]
- Output
- 7
- Input
- arg1 = [-3, -1, -2]
- Output
- -1
+12 hidden tests on Submit
Hints
Open them one at a time. Each one gives away a little more.
Focus on runs that end exactly at one position. How is the best run ending here related to the best run ending at the position just before it?
A run ending at the current element either continues the run that ended just before it or starts fresh at this element. Continuing only helps when that earlier run has a positive sum.
Walk the list once and keep two numbers: the best sum of a run ending at the current element, and the best sum seen so far. Start both at the first element, so a list of only negative numbers still returns its largest element.
A full walkthrough of this problem is on its way.
Similar problems
Problems that use the same ideas. Solving two or three of them is what makes a pattern stick.
Python
def maxSubArray(nums):
# Write code hereCase 1
Case 2
Input
arg1 = [2, -4, 3, -1, 5, -6, 1]
Expected
7