题目
- 最大子序和
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
思路
数组中找最大,考虑动态规划
状态:dp[i]:到位置 i 为止,已有的连续最大和。
状态方程:dp[i] = max(dp[i - 1] , 0) + nums[i]
走到 i 位置,如果前一个状态的dp[i-1]小于0,那就重新从这个位置开始连续数,如果大于0,则算上前面的。
当前状态只和前面一个状态有关,dp[i]和dp[i - 1]可以用一个变量表示。
currMax = Math.max(currMax, 0) + nums[i];
class Solution {
public int maxSubArray(int[] nums) {
// 思路。dp[i] = max(dp[i-1], 0) + nums[i]
if(nums == null || nums.length == 0) return 0;
int currMax = nums[0];
int ans = nums[0];
for(int i = 1; i < nums.length; i++) {
if(currMax > 0) {
currMax = currMax + nums[i];
}else {
currMax = nums[i];
}
ans = Math.max(ans, currMax);
}
return ans;
}
}
class Solution {
public int maxSubArray(int[] nums) {
// dp[i] = max(dp[i-1], 0) + nums[i];
if(nums == null || nums.length == 0) return 0;
int currMax = nums[0];
int ans = nums[0];
for(int i = 1; i < nums.length; i++) {
currMax = Math.max(currMax, 0) + nums[i];
ans = Math.max(ans, currMax);
}
return ans;
}
}
出错点:
- 没有用ans : ans = Math.max(ans, currMax); 因为currMax最后不一定就是最大的,比如后面有很多负数,正数。它的最大状态很有可能在中间。
- currMax = nums[0] , ans = nums[0]; 考虑只有一个元素,且元素为负数或整数的情况。
因为for从i =1 开始。