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
< ? php function alternateSubarray ( $ arr , $ n ) { $ count = 1 ; $ prev = $ arr [ 0 ] ; for ( $ i = 1 ; $ i < $ n ; ++ $ i ) { if ( ( $ arr [ $ i ] ^ $ prev ) == 0 ) { while ( $ count ) echo $ count -- , " ▁ " ; } ++ $ count ; $ prev = $ arr [ $ i ] ; } while ( $ count ) echo $ count -- , " ▁ " ; } $ arr = array ( 1 , 0 , 1 , 0 , 0 , 1 ) ; $ n = sizeof ( $ arr ) ; alternateSubarray ( $ arr , $ n ) ; ? >