Longest alternating subsequence | 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
function LAS ( arr , n ) { let inc = 1 ; let dec = 1 ; for ( let 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 Math . max ( inc , dec ) ; } let arr = [ 10 , 22 , 9 , 33 , 49 , 50 , 31 , 60 ] ; let n = arr . length ; document . write ( LAS ( arr , n ) ) ;