Longest alternating sub | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void alternateSubarray ( bool arr [ ] , int n ) { int count = 1 ; int prev = arr [ 0 ] ; for ( int i = 1 ; i < n ; ++ i ) { if ( ( arr [ i ] ^ prev ) == 0 ) { while ( count ) cout << count -- << " ▁ " ; } ++ count ; prev = arr [ i ] ; } while ( count ) cout << count -- << " ▁ " ; } int main ( ) { bool arr [ ] = { 1 , 0 , 1 , 0 , 0 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; alternateSubarray ( arr , n ) ; return 0 ; }