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
def LAS ( arr , n ) : NEW_LINE INDENT inc = 1 NEW_LINE dec = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] ) : NEW_LINE INDENT inc = dec + 1 NEW_LINE DEDENT elif ( arr [ i ] < arr [ i - 1 ] ) : NEW_LINE INDENT dec = inc + 1 NEW_LINE DEDENT DEDENT return max ( inc , dec ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 22 , 9 , 33 , 49 , 50 , 31 , 60 ] NEW_LINE n = len ( arr ) NEW_LINE print ( LAS ( arr , n ) ) NEW_LINE DEDENT