# Maximum and subsequence Problems

Source: Internet
Author: User

// Hhh. cpp: defines the entry point of the console application.
//

# Include "stdafx. H"
# Include <iostream>

Using namespace STD;

Int maxsub_sum (const int A [], int N, Int & seqstart, Int & seqend)
{
Int thissum, maxsum, I, j;
Thissum = 0;
Maxsum = 0;
I = 0;
/*
From left to right. If the result is continuously increasing, thissum and maxsum will increase together.
If a negative number is encountered, it is also added to thissum. In this case, thissum <maxsum is not added to maxsum.
Check whether thissum will recover. If thissum does not continue to recover, it will not or the ripple will fall.
If it falls to 0, the previous rising and falling stages can be abandoned and a new stage starts. At this time, thissum = 0,
However, maxsum retains the maximum value of the previous rising phase.
Then, thissum starts to analyze the new sub-segments. If there are sub-segments larger than the current maxsum, replace them. (Maxsum in the previous rising stage will be completely discarded)
The time complexity is O (n)

*/
For (j = 0; j <n; j ++)
{
Thissum + = A [J];
If (thissum> maxsum)
{
Maxsum = thissum;
Seqstart = I;
Seqend = J;
}
Else if (thissum <0)
{
I = J + 1;
Thissum = 0;
}

}

Return maxsum;
}

Int _ tmain (INT argc, _ tchar * argv [])
{
Int A [] = {1, 2,-1, 1, 3, 2,-2, 3,-1, 5,-7, 3, 2,-2, -1 };
Int size = sizeof (a)/sizeof (INT );
Int start = 0;
Int end = 0;
Int maxsum = maxsub_sum (A, size, start, end );
Cout <maxsum <"<start <" "<End <Endl;

Return 0;
}

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.