Longest alternating subsequence | C ++ program for above approach ; Function for finding longest alternating subsequence ; " inc " and " dec " initialized as 1 as single element is still LAS ; Iterate from second element ; " inc " changes iff " dec " changes ; " dec " changes iff " inc " changes ; Return the maximum length ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LAS ( int arr [ ] , int n ) { int inc = 1 ; int dec = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] ) { inc = dec + 1 ; } else if ( arr [ i ] < arr [ i - 1 ] ) { dec = inc + 1 ; } } return max ( inc , dec ) ; } int main ( ) { int arr [ ] = { 10 , 22 , 9 , 33 , 49 , 50 , 31 , 60 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << LAS ( arr , n ) << endl ; return 0 ; }