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