Click here to Skip to main content
15,899,025 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

C++
#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;

}


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 ?
Posted
Updated 3-May-10 16:57pm
v4

1 solution

The biggest problem that I see is that last is always going to equal in

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 that i value as the last value. so
C++
if (sum > maxsum)
{
    maxsum = sum;
    last = i;
}


Then, you just need to change the last for from i<last to i<=last.

That should give you what you're expecting.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900