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 ; Prlet lengths of binary subarrays . ; Driver program
function alternateSubarray ( arr , n ) { let len = new Array ( n ) ; len [ n - 1 ] = 1 ; for ( let i = n - 2 ; i >= 0 ; -- i ) { if ( arr [ i ] ^ arr [ i + 1 ] == 1 ) len [ i ] = len [ i + 1 ] + 1 ; else len [ i ] = 1 ; } for ( let i = 0 ; i < n ; ++ i ) document . write ( len [ i ] + " " ) ; } let arr = [ 1 , 0 , 1 , 0 , 0 , 1 ] ; let n = arr . length ; alternateSubarray ( arr , n ) ;