0053. Maximum Subarray
Easy | Array + DP | 40 ms (97.39%), 14.1 MB (71.67%)
Last updated
Was this helpful?
Easy | Array + DP | 40 ms (97.39%), 14.1 MB (71.67%)
Last updated
Was this helpful?
Source: GitHub:
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
The difficult part is to figure out whether a negative number is "worth" keeping in a subarray. We could use the concept localMax and globalMax to find out.
localMax = current sum = previous sum + nums[i] If current sum is smaller than a new number, we take new number as current sum. Otherwise, we keep adding this new number to the current sum.
globalMax = max sum = final answer We check whether localMax (or current sum) is larger than the globalMax in each iteration. If so, we have new value of max sum