Longest alternating sub | Java program to calculate longest alternating sub - array for each index elements ; 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
class GFG { static void alternateSubarray ( boolean arr [ ] , int n ) { int len [ ] = new int [ n ] ; len [ n - 1 ] = 1 ; for ( int i = n - 2 ; i >= 0 ; -- i ) { if ( arr [ i ] ^ arr [ i + 1 ] == true ) len [ i ] = len [ i + 1 ] + 1 ; else len [ i ] = 1 ; } for ( int i = 0 ; i < n ; ++ i ) System . out . print ( len [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { boolean arr [ ] = { true , false , true , false , false , true } ; int n = arr . length ; alternateSubarray ( arr , n ) ; } }