0053. Maximum Subarray
Easy | Array + DP | 40 ms (97.39%), 14.1 MB (71.67%)
Source: LeetCode - Maximum Subarray GitHub: Solution / Performance
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Whenever you see a question that asks for the maximum or minimum of something, consider Dynamic Programming as a possibility.
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
Last updated