Longest alternating subsequence with maximum sum | Set 2 | C ++ Program to implement the above approach ; Function to check the sign of the element ; Function to calculate and return the maximum sum of longest alternating subsequence ; Iterate through the array ; Stores the first element of a sequence of same sign ; Traverse until an element with opposite sign is encountered ; Update the maximum ; Update the maximum sum ; Update i ; Return the maximum sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sign ( int x ) { if ( x > 0 ) return 1 ; else return -1 ; } int findMaxSum ( int arr [ ] , int size ) { int max_sum = 0 , pres , i , j ; for ( i = 0 ; i < size ; i ++ ) { pres = arr [ i ] ; j = i ; while ( j < size && sign ( arr [ i ] ) == sign ( arr [ j ] ) ) { pres = max ( pres , arr [ j ] ) ; j ++ ; } max_sum = max_sum + pres ; i = j - 1 ; } return max_sum ; } int main ( ) { int arr [ ] = { -2 , 8 , 3 , 8 , -4 , -15 , 5 , -2 , -3 , 1 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMaxSum ( arr , size ) ; return 0 ; }