Answer to Question #325754 in C++ for Ridhi

Question #325754

You are given an array of N non-negative integers: A1A2, ..., 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 Ai1Ai2, ..., 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.


1
Expert's answer
2022-04-08T03:48:02-0400
#include <iostream>
using namespace std;


int max_alt_subseq(int A[], int n) {
    int sum1=0, sum2=0;


    for (int i=0; i<n; i++) {
        if (i%2) {
            sum1 += A[i];
        }
        else {
            sum2 += A[i];
        }
    }
    return sum1 > sum2 ? sum1 : sum2;
}

int main() {
    int A[] = { 1, 2, 3, 4, 5, 4, 3, 2, 1};
    int n = sizeof(A) / sizeof(A[0]);

    int sum = max_alt_subseq(A, n);

    cout << "The maximum sum of alternative subsequences is " << sum << endl;

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS