text: Count subarrays having an equal count of 0 s and 1 s segregated | C ++ program for the above approach ; Function to count subarrays having equal count of 0 s and 1 s with all 0 s and all 1 s grouped together ; Stores the count ; Initialize cur with first element ; If the next element is same as the current element ; Increment count ; Update curr ; Iterate over the array count ; Consider the minimum ; Driver code ; Given arr [ ] ; Function Call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void countSubarrays ( int A [ ] , int N ) { int res = 0 ; int curr = A [ 0 ] ; vector < int > cnt = { 1 } ; for ( int c = 1 ; c < N ; c ++ ) { if ( A == curr ) cnt [ cnt . size ( ) - 1 ] ++ ; else curr = A ; cnt . push_back ( 1 ) ; } for ( int i = 1 ; i < cnt . size ( ) ; i ++ ) { res += min ( cnt [ i - 1 ] , cnt [ i ] ) ; } cout << ( res - 1 ) ; } int main ( ) { int A [ ] = { 1 , 1 , 0 , 0 , 1 , 0 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; countSubarrays ( A , N ) ; return 0 ; }