Maximum subsequence problem:
That is, find a subsequence in a given sequence to make it and maximize it in all subsequences.
The code is implemented as follows:
[Cpp]
# Include <iostream>
# Include <vector>
Using namespace std;
Const unsigned int N = 5;
Int maxSubSum1 (const vector <int> &)
{
Int max_sum = 0;
Int begin = 0;
Int interval = 0;
For (unsigned int I = 0; I <a. size (); I ++)
{
For (unsigned int j = I; j <a. size (); j ++)
{
Int this_sum = 0;
For (unsigned int k = I; k <= j; k ++)
{
This_sum + = a [k];
}
If (this_sum> max_sum)
{
Max_sum = this_sum;
Begin = I;
Interval = j;
}
}
}
Cout <"The biggest subarray is:" <endl;
For (; begin <= interval; begin ++)
{
Cout <a [begin] <"\ t ";
}
Return max_sum;
}
//
Int maxSubSum2 (const vector <int> &)
{
Int max_sum = 0;
Int begin = 0;
Int interval = 0;
For (unsigned int I = 0; I <a. size (); I ++)
{
Int this_sum = 0;
For (unsigned int j = I; j <a. size (); j ++)
{
This_sum + = a [j];
If (this_sum> max_sum)
{
Max_sum = this_sum;
Begin = I;
Interval = j;
}
}
}
Cout <"The biggest subarray is:" <endl;
For (; begin <= interval; begin ++)
{
Cout <a [begin] <"\ t ";
}
Return max_sum;
}
//
Int maxSubSum3 (const vector <int> &)
{
Int max_sum = 0;
Int this_sum = 0;
Unsigned int begin = 0;
Unsigned int count = 0;
For (unsigned int j = 0; j <a. size (); j ++)
{
This_sum + = a [j];
Count ++;
If (this_sum> max_sum)
{
Max_sum = this_sum;
Begin = (j + 1)-count;
} Www.2cto.com
Else if (this_sum <0)
{
This_sum = 0;
Count = 0;
}
}
Cout <"The biggest subarray is:" <endl;
For (unsigned int I = begin; I <begin + count; I ++)
{
Cout <a [I] <"\ t ";
}
Return max_sum;
}
Int main ()
{
Vector <int> array (N );
Int sub_sum = 0;
// MaxSubSum1 (array );
Cout <"Please input" <N <"number to the array:" <endl;
For (unsigned int I = 0; I <N; I ++)
{
Cin> array [I];
}
Sub_sum = maxSubSum3 (array );
Cout <"\ nThe biggest sum of the subarray is:" <endl;
Cout <sub_sum <endl;
Return 0;
}
Three different methods are provided in the Code. The first time complexity is O (n ^ 3 ). The second type is O (n ^ 2 ). The third type is O (n ).