获取不正确的子序列,该子序列给出最大和 [英] Getting incorrect subsequence that gives the maximal sum
问题描述
为什么我没有得到给出最大和的正确子序列? (尽管我得到了正确的最大和).例如:-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 ?
推荐答案
我看到的最大问题是last
总是等于in
您输入正确的第一个电话号码吗?
你有什么进步吗?我进行了一些修改就可以在C#中使用它.它们是很小的修改.
在进行过程中,如果您知道到目前为止已达到最大和,则需要将该i
值设置为last
值.所以
The biggest problem that I see is thatlast
is always going to equalin
Are you getting the right first number?
Have you made any progress? I got it to work in C# with a few modifications. They''re pretty small modifications.
As you''re going, if you know that you''ve reached the maxsum so far, you want to set thati
value as thelast
value. so
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.
这篇关于获取不正确的子序列,该子序列给出最大和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!