问题描述
为什么我没有得到给出最大和的正确子序列? (尽管我得到了正确的最大和).例如:-1,2,-1,3,-5应该给4作为最大和并显示2,-1,3
Why am I not getting the correct subsequence that gives the maximal sum? (though I am getting the correct maximal sum)..for example: -1 , 2 , -1, 3, -5 should give 4 as maximal sum and should display 2, -1 , 3
#include<iostream>
using namespace std;
void main ()
{
int in=0, list[300], i, sum=0 , maxsum=0, first=0, last;
cout<<"Enter a list of integers (ending with -999) \n";
cin>>list[in];
while (list[in]!= -999)
{
in++;
cin>>list[in];
}
for (i=0 ; i<in ; i++)
{
sum+= list[i];
if(sum>maxsum)
{
maxsum=sum;
}
else if (sum<0)
{
sum=0;
first= i+1;
}
}
last=i;
for (i=first ; i<last ; i++)
{
cout<<list[i]<<" ";
}
cout<<endl;
cout<<"Maximum sum is : \n"<<maxsum<<endl;
}
更新SM:下次发布问题时,能否请您输入适当的标题?标题必须简短.整个问题不需要填写!
更新MG:现在我们可以得到问题的最后一部分了吗?
UPDATE SM: Can you please put a proper title next time you post the question? Title needs to be short and brief. Entire question does not needs to be put up in it!
Update MG:And can we now get the last part of the question ?
推荐答案
if (sum > maxsum)
{
maxsum = sum;
last = i;
}
然后,您只需要将最后一个从i<last
更改为i<=last
.
那应该给您您期望的东西.
Then, you just need to change the last for from i<last
to i<=last
.
That should give you what you''re expecting.
这篇关于获取不正确的子序列,该子序列给出最大和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!