Longest alternating sub | Function to calculate alternating sub - array for each index of array elements ; Initialize count variable for storing length of sub - array ; Initialize ' prev ' variable which indicates the previous element while traversing for index 'i ; If both elements are same , print elements because alternate element is not found for current index ; print count and decrement it . ; Increment count for next element ; Re - initialize previous variable ; If elements are still available after traversing whole array , print it ; Driver Code
def alternateSubarray ( arr , n ) : NEW_LINE INDENT count = 1 NEW_LINE DEDENT ' NEW_LINE INDENT prev = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( ( arr [ i ] ^ prev ) == 0 ) : NEW_LINE INDENT while ( count ) : NEW_LINE INDENT print ( count , end = " ▁ " ) NEW_LINE count -= 1 NEW_LINE DEDENT DEDENT count += 1 NEW_LINE prev = arr [ i ] NEW_LINE DEDENT while ( count ) : NEW_LINE INDENT print ( count , end = " ▁ " ) NEW_LINE count -= 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 1 , 0 , 0 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE alternateSubarray ( arr , n ) NEW_LINE DEDENT