Minimum number of alternate subsequences required to be removed to empty a Binary String | C ++ program for the above approach ; Function to find the minimum number of operations to empty a binary string ; Stores the resultant number of operations ; Stores the number of 0 s ; Stores the number of 1 s ; Traverse the given string ; To balance 0 with 1 if possible ; Increment the value of cn0 by 1 ; To balance 1 with 0 if possible ; Increment the value of cn1 ; Update the maximum number of unused 0 s and 1 s ; Print the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOpsToEmptyString ( string s ) { int ans = INT_MIN ; int cn0 = 0 ; int cn1 = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == '0' ) { if ( cn1 > 0 ) cn1 -- ; cn0 ++ ; } else { if ( cn0 > 0 ) cn0 -- ; cn1 ++ ; } ans = max ( { ans , cn0 , cn1 } ) ; } cout << ans ; } int main ( ) { string S = "010101" ; minOpsToEmptyString ( S ) ; return 0 ; }