

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum sum alternating subsequence in C++
In this tutorial, we will be discussing a program to find maximum sum alternating subsequence.
For this we will be provided with an array of integers. Our task is to find the maximum sum of an alternating subsequence i.e sequence which is first decreasing, then increasing, then decreasing and so on.
Example
#include<bits/stdc++.h> using namespace std; //returning maximum sum alternating series int maxAlternateSum(int arr[], int n) { if (n == 1) return arr[0]; int dec[n]; memset(dec, 0, sizeof(dec)); int inc[n]; memset(inc, 0, sizeof(inc)); dec[0] = inc[0] = arr[0]; int flag = 0 ; for (int i=1; i<n; i++) { for (int j=0; j<i; j++) { if (arr[j] > arr[i]) { dec[i] = max(dec[i], inc[j]+arr[i]); flag = 1; } else if (arr[j] < arr[i] && flag == 1) inc[i] = max(inc[i], dec[j]+arr[i]); } } int result = INT_MIN; for (int i = 0 ; i < n; i++) { if (result < inc[i]) result = inc[i]; if (result < dec[i]) result = dec[i]; } return result; } int main() { int arr[]= {8, 2, 3, 5, 7, 9, 10}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Maximum sum = " << maxAlternateSum(arr , n ) << endl; return 0; }
Output
Maximum sum = 25
- Related Questions & Answers
- Maximum sum alternating subsequence in C++ program
- Maximum Sum Increasing Subsequence
- Maximum Sum Decreasing Subsequence in C++
- Maximum Sum Increasing Subsequence | DP-14 in C++
- Maximum Sum Increasing Subsequence using DP in C++ program
- Maximum subsequence sum such that no three are consecutive
- Maximum Sum Increasing Subsequence using Binary Indexed Tree in C++
- Maximum sum subsequence with at-least k distant elements in C++
- Maximum Sum Increasing Subsequence using Binary Indexed Tree in C++ program
- Maximum subsequence sum such that no three are consecutive in C++ Program
- Maximum sum subsequence with at-least k distant elements in C++ program
- Constrained Subsequence Sum in C++
- Sum of Subsequence Widths in C++
- Program to find length of longest alternating subsequence from a given list in Python
- Maximum product of an increasing subsequence in C++
Advertisements