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
First line of the input contains an integer T denoting the number of test cases.
The first line of each test case contains an integer N denoting the number of elements in the array. Second line contains N space-separated integers A1, A2, ..., AN denoting the array A
Input:
1
3
1 2 5
Output:
6
For the given array [1, 2, 5], there are 7 non-empty subsequences out of which there are 4 alternating subsequences. These will be {[1], [2], [5], [1, 5]}. The alternating subsequence [1, 5] will have the largest sum i.e 6.
#include <iostream>
using namespace std;
int main () {
int N, A[10], T;
int temp = 0;
cout << "Enter the number of test cases: ";
cin >> T;
for (int x = 0; x < T; x++) {
cout << "Enter the number of elements in the array:";
cin >> N;
cout << "Enter the elements of the array: ";
for(int i = 0; i < N; i++) {
cin >> A[i];
}
int sum = A[N-1] + A[N-2];
cout << "Sum is: " << sum << endl;
}
return 0;
}
Comments
Leave a comment