C++ 数组中的连续最大和-动态规划

C++ 数组中的连续最大和-动态规划,c++,arrays,logic,dynamic-programming,C++,Arrays,Logic,Dynamic Programming,我正在学习关于动态规划的教程。下面是以下链接: 他们得出了一个关系: M[j] = Max (A[j], A[j] + M[j-1]) 但是在实现这个的实际代码中,我无法理解他们是如何使用它的 //Initialize the first value in (M) and (b) M[1] = A[1]; b[1] = 1; //Initialize max as the first element in (M) //we will keep updating max u

我正在学习关于动态规划的教程。下面是以下链接: 他们得出了一个关系:

M[j] = Max (A[j], A[j] + M[j-1])  
但是在实现这个的实际代码中,我无法理解他们是如何使用它的

//Initialize the first value in (M) and (b)  
M[1] = A[1];  
b[1] = 1;  

//Initialize max as the first element in (M)  
//we will keep updating max until we get the  
//largest element in (M) which is indeed our  
//MCSS value. (k) saves the (j) position of   
//the max value (MCSS)  
int max = M[1];  
int k = 1;  

//For each sub sequence ending at position (j)  
for (int j = 2; j <= n; j++)  
{  
    //M[j-1] + A[j] > A[j] is equivalent to M[j-1] > 0  
    if (M[j-1] > 0)  
    {  
        //Extending the current window at (j-1)  
        M[j] = M[j-1] + A[j];  
        b[j] = b[j-1];  
    }  
    else  
    {  
        //Starting a new window at (j)  
        M[j] = A[j];  
        b[j] = j;  
    }  

    //Update max and save (j)  
    if (M[j] > max)   
    {  
        max = M[j];  
        k = j;  
    }  
}  

print ("MCSS value = ", max,  " starts at ", b[k],  " ends at ", k);  

您的问题的答案已在这一行给出:

//M[j-1] + A[j] > A[j] is equivalent to M[j-1] > 0  
if语句在A[j]和M[j-1]+A[j]之间选择较大的值。 你会更清楚吗

if (M[j-1] + A[j] > A[j]) // is exact the same thing as M[j-1] > 0, but less elegant
{   
     M[j] = M[j-1] + A[j];
     b[j] = b[j-1];
}
else
{
    M[j] = A[j];
    b[j] = j;
}

不清楚与。嗨,阿美。这个问题事实上与前一个问题有关。问题是在理解了给定文章背后的所有理论之后,当我看到实现时,它看起来完全不同,我的意思是为什么他们不能使用他们推导的公式???
if (M[j-1] + A[j] > A[j]) // is exact the same thing as M[j-1] > 0, but less elegant
{   
     M[j] = M[j-1] + A[j];
     b[j] = b[j-1];
}
else
{
    M[j] = A[j];
    b[j] = j;
}