Longest alternating ( positive and negative ) subarray starting at every index | Python3 program to find longest alternating subarray starting from every index . ; Fill count [ ] from end . ; Print result ; Driver Code
def longestAlternating ( arr , n ) : NEW_LINE INDENT count = [ None ] * n NEW_LINE count [ n - 1 ] = 1 NEW_LINE i = n - 2 NEW_LINE while i >= 0 : NEW_LINE INDENT if ( arr [ i ] * arr [ i + 1 ] < 0 ) : NEW_LINE INDENT count [ i ] = count [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ i ] = 1 ; NEW_LINE DEDENT i = i - 1 NEW_LINE DEDENT i = 0 NEW_LINE while i < n : NEW_LINE INDENT print ( count [ i ] , end = " ▁ " ) NEW_LINE i = i + 1 NEW_LINE DEDENT DEDENT a = [ - 5 , - 1 , - 1 , 2 , - 2 , - 3 ] NEW_LINE n = len ( a ) NEW_LINE longestAlternating ( a , n ) ; NEW_LINE