LeetCode 53.最大子序和_动态规划


​ https://leetcode-cn.com/problems/maximum-subarray/​

思路:
动态规划的是首先对数组进行遍历,当前最大连续子序列和为 pre,结果为 max。
如果 pre > 0,则说明 pre 对结果有增益效果,则 pre保留并加上当前遍历数字。
如果 pre <= 0,则说明 pre 对结果无增益效果,需要舍弃,则 pre 直接更新为当前遍历数字。
每次比较 pre 和 max的大小,将最大值置为max,遍历结束返回结果
时间复杂度:O(n)

1.动态规划

class Solution {
public int maxSubArray(int[] nums) {
if(nums == null || nums.length ==0){
return 0;
}
//dp[i]表示以nums[i]结尾的最大子序和
int[] dp = new int[nums.length];
dp[0] = nums[0];
for(int i = 1; i< nums.length;i++){
//如果以nums[i-1]为结尾的最大子序和大于等于0
//那么以nums[i]为结尾的最大子序和为为dp[i-1]+nums[i]
if(dp[i-1]>=0){
dp[i] = dp[i-1]+nums[i];
}else{
//如果以nums[i-1]为结尾的最大子序和小于0
//那么久不要前面的了,从新开始算
dp[i] = nums[i];
}
}
int max = dp[0];
for(int i = 1;i<dp.length;i++){
max = Math.max(max,dp[i]);
}

return max;

}
}

1.1优化

class Solution {
public int maxSubArray(int[] nums) {
if (nums.length == 0){
return 0;
}

int pre = nums[0];//用来存储以nums[i-1]的当前子序和
int max = nums[0];//当前的最大子序和
for(int i = 1; i < nums.length; i++){
if(pre>0){
pre += nums[i];
}else{
pre = nums[i];
}
//更新当前最大的子序和
max = Math.max(pre,max);
}

return max;

}
}