[leetCode]53. 最大子序和
解法一 贪心算法
思路:如果当前指针之前元素小于0则丢弃之前的数列
class Solution {
public int maxSubArray(int[] nums) {
int sum = 0;
int preSum = nums[0];
int maxSum = nums[0];
for(int i = 1; i < nums.length; i++){
if(preSum >= 0){
sum = nums[i]+preSum;
maxSum = Math.max(sum, maxSum);
preSum = sum;
}else{
preSum = nums[i];//丢弃之前的数列,重新开始做累加
maxSum = Math.max(preSum,maxSum);
}
}
return maxSum;
}
}
简化版本:
class Solution {
public int maxSubArray(int[] nums) {
int preSum = nums[0];
int maxSum = nums[0];
for(int i = 1; i < nums.length; i++){
preSum = Math.max(nums[i],preSum+nums[i]);//如果当前和小于之前的和则抛弃前面的子数列,preSum+nums[i]为当前和
maxSum = Math.max(preSum, maxSum);
}
return maxSum;
}
}
解法二 动态规化
思路:如果前一个元素大于0,则加到当前元素上
class Solution {
public int maxSubArray(int[] nums) {
for(int i = 1; i < nums.length; i++){
if(nums[i - 1] > 0){
nums[i] += nums[i-1];
}
}
Arrays.sort(nums);
return nums[nums.length-1];
}
}