maximum- contious -subarray-sum的输出没有正确显示

Output of maximum-contigous-subarray-sum is not showing correctly

本文关键字:显示 输出 contious -subarray-sum maximum-      更新时间:2023-10-16

我正在遵循一个网站的教程(下面的链接),从那里我试图实现"最大连续和子数组"的标准问题。但他们尝试了他们的代码与示例数组:{15,-1,-3,4,-5}显示的答案是:" SMCSS值= 4开始于3,结束于3"但它应该显示最大值为15,所以开始和结束值为1。代码如下:有什么不对我该怎么修改 link:http://www.8bitavenue.com/2011/11/dynamic-programming-maximum-contiguous-sub-sequence-sum/

    #include<iostream>
    #include<stdio.h>
    //Initialize the first value in (M) and (b)  
    using namespace std;
    int main(){
    int M[8],b[8];
    int A[] = {15,-1,-3,4,-5};

    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;  
    int n = sizeof(A)/sizeof(int);
    cout<<n;
    //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;  
        }  
    }  
    cout<<"MCSS value = "<<max<<"starts at "<<b[k]<<"ends at"<<k;
    return 0;
} 

在深入研究索引之前有两件事:

  1. 数组从C++中的0开始编号。所以我假设这一切都是从M[0] = A[0]; b[0] = 0;

  2. 开始的
  3. 你应该考虑使用std::vector,这是C++处理数组的方式。

正确代码

#include<iostream>
#include<stdio.h>
//Initialize the first value in (M) and (b)
using namespace std;
int main()
{
    int M[8],b[8];
    int A[] = {15,-1,-3,4,-5};
    M[0] = A[0];
    b[0] = 0;
    //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[0];
    int k = 0;
    int n = sizeof(A)/sizeof(int);
    cout<<n<<endl;
    //For each sub sequence ending at position (j)
    for (int j = 1; 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;
        }
    }
    cout<<"MCSS value = "<<max<<" starts at "<<b[k]<<" ends at"<<k;
    return 0;
}