maximum- contious -subarray-sum的输出没有正确显示
Output of maximum-contigous-subarray-sum is not showing correctly
我正在遵循一个网站的教程(下面的链接),从那里我试图实现"最大连续和子数组"的标准问题。但他们尝试了他们的代码与示例数组:{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;
}
在深入研究索引之前有两件事:
-
数组从
C++
中的0
开始编号。所以我假设这一切都是从M[0] = A[0]; b[0] = 0;
开始的 你应该考虑使用
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;
}
相关文章:
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- C++ 构造函数未显示输出
- 显示C++输出而不返回值
- 为什么输出窗口上没有显示输出?
- 为什么我的代码块上没有显示输出?
- C++ 程序不显示输出
- isPalindrome不显示输出,isPalindrome函数未使用字符串输入作为字符串参数进行测试
- 如何从amd gpus的显示输出中获取图像数据
- 插入了 C++ 数组字符串数据,但在显示输出时不显示
- 程序不会在必须时结束并显示输出
- 为什么我的前缀中缀代码不显示输出
- 函数显示输出和输入时出现问题
- 为什么我的程序多次显示输出
- 二进制搜索 - 代码编译并运行后不显示输出
- 字符串流未显示输出
- 为什么当我使用 cout 显示输出时,必须将按位运算符(例如 &,|,等)括在括号中?
- 这段代码可编译,但在visualstudio2015社区中运行(c++)时不显示输出
- Jupyter笔记本未显示C 输出(COUT)
- 尝试拆分循环链表.显示输出但崩溃.在 IDEone 中显示运行时错误
- Q未显示输出