Maximum Subarray
Examples
Example 1:
Input: nums = [2,-3,4,-2,2,1,-1,4]
Output: 8
Explanation:
Example 2:
Input: nums = [-1]
Output: -1
Example 1:
Input: nums = [2,-3,4,-2,2,1,-1,4]
Output: 8
Explanation:
Example 2:
Input: nums = [-1]
Output: -1
Given an array of integers nums, find the subarray with the largest sum and return the sum.
A subarray is a contiguous non-empty sequence of elements within an array.
The subarray [4,-2,2,1,-1,4] has the largest sum 8.
1 <= nums.length <= 1000-1000 <= nums[i] <= 1000Use Kadane's algorithm. Track the best subarray sum ending at the current index and the global maximum. At each step, either extend the previous subarray or start fresh at the current number.
Any maximum subarray ending at index i is either the current element alone or the previous best ending at i-1 plus the current element. Taking the max of these at each step yields the best ending here, and the global max over all endings is the answer.
O(n)O(1)class Solution:
def maxSubArray(self, nums: List[int]) -> int:
best = nums[0]
current = nums[0]
for num in nums[1:]:
current = max(num, current + num)
best = max(best, current)
return best