Likou--53. Maximum Subsequence Sum--Dynamic Programming + Rolling Array

  1. Maximum sub-order sum
    Given an integer array nums, find a continuous sub-array with the largest sum (the sub-array contains at least one element), and return its largest sum.
示例:

输入: [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:

如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。

For detailed explanation, see my other blog

Code:

#define Max(a,b) ((a)>(b)?(a):(b))
int maxSubArray(int* nums, int numsSize){
    
    
    if(numsSize==0)
        return 0;
    int dp[numsSize];
    int max = nums[0];
    dp[0]=nums[0];
    for(int i=1;i<numsSize;i++)
    {
    
    
        dp[i]=Max(dp[i-1]+nums[i],nums[i]);
        max=Max(dp[i],max);
    }
    return max;
}

Of course, there may be another way , that is, we set dp[i] as the size of the largest subsequence when there are i numbers.
So similar we can get the following code:

int max(int a,int b,int c)
{
    
    
    int temp = a>b?a:b;
    return temp>c?temp:c;
}
int maxSubArray(int* nums, int numsSize){
    
    
    if(numsSize==0)
        return 0;
    int dp[numsSize+1];
    dp[1]=nums[0];
    for(int i=2;i<=numsSize;i++)
    {
    
    
        dp[i]=max(dp[i-1]+nums[i-1],nums[i-1],dp[i-1]);//会出现不连续的情况
    }
    return dp[numsSize];
}

But we will find the wrong place , that is, because our dp[i] only represents the size of the largest subsequence when there are i numbers, it does not necessarily include the i-th number, so dp[i-1]+ in the code nums[i-1] is not necessarily continuous at this time. So don't write like this. And our previous one can be because we defined the subscript i as the end, so it must be continuous.

Scrolling array optimization:

int Max(int x,int y)
{
    
    
    return x>y?x:y;
}
int maxSubArray(int* nums, int numsSize){
    
    
    if(numsSize==0)
    return 0;
    int first,second;
    first=nums[0];
    int max = first;
    for(int i=1;i<numsSize;i++)
    {
    
    
        second=Max(first+nums[i],nums[i]);
        max=Max(second,max);
        first=second;
    }
    return max;
}

Insert picture description here

Guess you like

Origin blog.csdn.net/xiangguang_fight/article/details/112726372