Find the Maximum Alternate Subsequence Sum from a given array | C ++ program to find the maximum alternating subsequence sum for a given array ; Function to find maximum alternating subsequence sum ; Initialize sum to 0 ; Calculate the sum ; Return the final result ; Driver Code ; Array initialization ; Length of array
#include <iostream> NEW_LINE using namespace std ; int maxAlternatingSum ( int arr [ ] , int n ) { int max_sum = 0 ; int i = 0 ; while ( i < n ) { int current_max = arr [ i ] ; int k = i ; while ( k < n && ( ( arr [ i ] > 0 && arr [ k ] > 0 ) || ( arr [ i ] < 0 && arr [ k ] < 0 ) ) ) { current_max = max ( current_max , arr [ k ] ) ; k += 1 ; } max_sum += current_max ; i = k ; } return max_sum ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , -1 , -2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxAlternatingSum ( arr , n ) ; return 0 ; }