题目描述
给定一个整数数组(有正数有负数),找出总和最大的连续数列,并返回总和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
我的题解(动态规划)
class Solution
{
public int maxSubArray(int[] nums)
{
int[] temp = new int[nums.length];
temp[0] = nums[0];
int max = temp[0];
for(int i=1;i<temp.length;i++) //通过前面结果求当前结果,如果前面结果<0,则不加,否则加上前面结果
{
if(temp[i-1]>0)
{
temp[i] = temp[i-1]+nums[i];
}
else
{
temp[i] = nums[i];
}
if(temp[i]>max)
max = temp[i];
}
return max;
}
}
leetcode评论区题解(和我的思路其实一样)
class Solution {
public int maxSubArray(int[] nums) {
int len = nums.length;
if (len == 0)
return 0;
if(len == 1)
return nums[0];
int[] dp = new int[len];
//初始状态
//dp[i]表示从左到右,包含元素nums[i]的最大和
dp[0] = nums[0];
int max = dp[0];
for (int i = 1; i < len; i++) {
dp[i] = Math.max(nums[i] + dp[i-1],nums[i]);
}
//寻找最大值
for (int i = 1; i < len; i++) {
if (dp[i] > max)
max = dp[i];
}
return max;
}
}