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 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 program
class GFG { static void alternateSubarray ( boolean arr [ ] , int n ) { int count = 1 ; boolean prev = arr [ 0 ] ; for ( int i = 1 ; i < n ; ++ i ) { if ( ( arr [ i ] ^ prev ) == false ) { while ( count > 0 ) { System . out . print ( count -- + " ▁ " ) ; } } ++ count ; prev = arr [ i ] ; } while ( count != 0 ) { System . out . print ( count -- + " ▁ " ) ; } } public static void main ( String args [ ] ) { boolean arr [ ] = { true , false , true , false , false , true } ; int n = arr . length ; alternateSubarray ( arr , n ) ; } }