Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
是给一个数组,在数组中找出元素相加和最大的连续子数组。
思路:
因为题中要求是连续子数组,连续很重要,省去了很多问题。
所以子数组只要一中断就要重新开始。
选择连续的思路可以看哪个和更大,是前面的部分加上当前元素更大,还是不要前面的了,从当前元素开始,只看当前元素本身更大。
相当于小型DP,而且最大值不一定在最后出现,要保存过程中的最大值。
public int maxSubArray(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
int localMax = nums[0];
int result = nums[0];
for(int i = 1; i < nums.length; i++) {
localMax = Math.max(localMax + nums[i], nums[i]);
result = Math.max(result, localMax);
}
return result;
}