数组中的连续最大总和 - 动态编程

时间:2015-05-09 10:52:46

标签: c++ arrays logic dynamic-programming

我正在关注动态编程的教程。请点击以下链接: http://www.8bitavenue.com/2011/11/dynamic-programming-maximum-contiguous-sub-sequence-sum/ 他们得出了一个关系:

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);  

我的问题是如何在此程序中使用派生公式?

他们不应该使用这样的东西:

for i in A:
  M[j] = Max (A[j], A[j] + M[j-1])  

1 个答案:

答案 0 :(得分:0)

您的问题的答案已在此行中给出:

//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;
}