Goal
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Key Idea (Intuition)
At each index, we decide whether to extend the best subarray ending at the previous index or start a new subarray at the current index.
If the running sum up to the previous index is negative, then starting fresh at the current index yields a larger value for maxEndingAtIndex than extending the negative sum.
Otherwise, it is better to extend the previous subarray by adding the current element.
Initialization
maxEndingAtIndex = nums[0]— best subarray sum that ends at index0.maxSoFar = maxEndingAtIndex— global best sum seen so far.- Start traversal at
i = 1.
Traversal
For each index i from 1 to n - 1:
-
Update the best ending here:
maxEndingAtIndex = max(maxEndingAtIndex, 0) + nums[i]
(IfmaxEndingAtIndexwas negative, reset to0to start a new subarray ati; otherwise, extend the previous subarray.) -
Update the global best:
maxSoFar = max(maxSoFar, maxEndingAtIndex)
Return
After the loop, return maxSoFar as the maximum subarray sum.