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
< ? php function alternateSubarray ( & $ arr , $ n ) { $ len = array_fill ( 0 , $ n , NULL ) ; $ len [ $ n - 1 ] = 1 ; for ( $ i = $ n - 2 ; $ i >= 0 ; -- $ i ) { if ( $ arr [ $ i ] ^ $ arr [ $ i + 1 ] == 1 ) $ len [ $ i ] = $ len [ $ i + 1 ] + 1 ; else $ len [ $ i ] = 1 ; } for ( $ i = 0 ; $ i < $ n ; ++ $ i ) echo $ len [ $ i ] . " ▁ " ; } $ arr = array ( 1 , 0 , 1 , 0 , 0 , 1 ) ; $ n = sizeof ( $ arr ) ; alternateSubarray ( $ arr , $ n ) ; ? >