You are given an array of N non-negative integers: A1, A2, ..., AN. An alternating subsequence is a subsequence in which the indices of any two consecutive elements differ by exactly two in the original array. That is, if Ai1, Ai2, ..., Aik is some subsequence, then for it to be an alternating subsequence, (i2 - i1 = 2), (i3 - i2 = 2), and so on should all hold true. Among all alternating subsequences, find the one which has maximum sum of elements, and output that sum.
Here is program:
int main()
{
int const size = 5;
int N[size]{3,5,3,1,20};
int sum = 0;
for (int i = 4; i >= 0 ; i--)
{
if (i == 0)
{
break;
}
sum += N[i] - N[i - 1];
}
cout << "Sum = "<< sum << endl;
}
Comments
Leave a comment