Minimum number of alternate subsequences required to be removed to empty a Binary String | Java 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
import java . util . * ; class GFG { static void minOpsToEmptyString ( String s ) { int ans = Integer . MIN_VALUE ; int cn0 = 0 ; int cn1 = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == '0' ) { if ( cn1 > 0 ) cn1 -- ; cn0 ++ ; } else { if ( cn0 > 0 ) cn0 -- ; cn1 ++ ; } ans = Math . max ( ans , Math . max ( cn0 , cn1 ) ) ; } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { String S = "010101" ; minOpsToEmptyString ( S ) ; } }