Leetcode 53. Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4]
,
the contiguous subarray [4,-1,2,1]
has the largest sum = 6
.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
思路 :
连续子数组最大和问题,当以第i-1 个数字结尾的子数组的和,小于0时,如果把这个负数与第i 个数相加,得到的结果第i 个数本身还要小,所以此时不能把它加到第i 个数上。
sum | 条件 |
---|---|
sum = nums[i] | 如果当前的sum 小于0 |
sum = sum + nums[i] | 如果当前的sum 大于0 |
class Solution {
public int maxSubArray(int[] nums) {
int max = nums[0];
int sum = nums[0];
for(int i = 1; i < nums.length; i++) {
if(sum <= 0) {
sum = nums[i];
}else {
sum += nums[i];
}
max = Math.max(max, sum);
}
return max;
}
}
注:学渣心里苦,不要学楼主,平时不努力,考试二百五,哭 ~