Maximum sum alternating subsequence in C++ program

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of n integers. Our task is to create a program to find the Maximum sum alternating subsequence starting from the first element of the array.

An alternating subsequence is a subsequence in which elements are increasing and decreasing in an alternating order i.e. first decreasing, then increasing, then decreasing. Here, the reverse alternating subsequence is not valid for finding the maximum sum.

Let’s take an example to understand the problem,

Input

arr[] = {5, 1, 6, 2, 4, 8, 9}

Output

27

Explanation

Starting element: 5, decrease: 1, increase: 6, decrease: 2, increase:4, N.A.
Here, we can use 4, 8, 9 as the last element of the subsequence.
Sum = 5 + 1 + 6 + 2 + 4 + 9 = 27

Solution Approach

To solve the problem, we will be using a dynamic programming approach. For this, we will be using two arrays one to store the maximum sum of elements ending with arr[i], where arr[i] is increasing. Other to store the maximum sum of elements ending with arr[i], where arr[i] is decreasing.

Then we will add elements one by checking if they are alternating subsequences. For each array, we will calculate the maximum sum until the index. And the return the maximum value after traversing n elements.

Example

Program to illustrate the working of our solution,

Live Demo

#include<iostream>
#include<cstring>
using namespace std;
int maxVal(int x, int y){
if(x > y)
return x;
return y;
}
int calcMaxSumAltSubSeq(int arr[], int n) {
int maxSum = −10000;
int maxSumDec[n];
bool isInc = false;
memset(maxSumDec, 0, sizeof(maxSumDec));
int maxSumInc[n];
memset(maxSumInc, 0, sizeof(maxSumInc));
maxSumDec[0] = maxSumInc[0] = arr[0];
for (int i=1; i<n; i++) {
for (int j=0; j<i; j++) {
if (arr[j] > arr[i]) {
maxSumDec[i] = maxVal(maxSumDec[i],
maxSumInc[j]+arr[i]);
isInc = true;
}
else if (arr[j] < arr[i] && isInc)
maxSumInc[i] = maxVal(maxSumInc[i],
maxSumDec[j]+arr[i]);
}
}
for (int i = 0 ; i < n; i++)
maxSum = maxVal(maxSum, maxVal(maxSumInc[i],
maxSumDec[i]));
return maxSum;
}
int main() {
int arr[]= {8, 2, 3, 5, 7, 9, 10};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"The maximum sum alternating subsequence starting is "<<calcMaxSumAltSubSeq(arr , n);
return 0;
}

Output

The maximum sum alternating subsequence starting is 25
Published on 09-Dec-2020 13:01:52