Longest alternating sub | Function to calculate alternating sub - array for each index of array elements ; Initialize the base state of len [ ] ; Calculating value for each element ; If both elements are different then add 1 to next len [ i + 1 ] ; else initialize to 1 ; Print lengths of binary subarrays . ; Driver code
def alternateSubarray ( arr , n ) : NEW_LINE INDENT len = [ ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT len . append ( 0 ) NEW_LINE DEDENT len [ n - 1 ] = 1 NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] ^ arr [ i + 1 ] == True ) : NEW_LINE INDENT len [ i ] = len [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT len [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( len [ i ] , " ▁ " , end = " " ) NEW_LINE DEDENT DEDENT arr = [ True , False , True , False , False , True ] NEW_LINE n = len ( arr ) NEW_LINE alternateSubarray ( arr , n ) NEW_LINE