Maximum Subarray
Given an integer array, find the subarray with the largest sum and return its sum.
Example
-2,1,-3,4,-1,2,1,-5,4
6
- Input:
numsis a list of integers, here-2,1,-3,4,-1,2,1,-5,4. A subarray is a contiguous, non-empty run . - Math: each run has sum , and the answer is the largest over all .
- The best run is indices to : . The is worth keeping because it connects to , and beats alone or alone.
- Stretching it further only hurts: the values before it, , and after it, , both add a negative amount.
- Output: a single integer,
6. Notice that adding up just the positive values () is not allowed — they are not contiguous. If every value were negative, the answer would be the single largest (least negative) element, since the run cannot be empty.
Constraints
- 1 <= len(nums) <= 10^5
- -10^4 <= nums[i] <= 10^4