Minimum number of alternate subsequences required to be removed to empty a Binary String | 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 resultant count ; Driver Code
def minOpsToEmptyString ( s ) : NEW_LINE INDENT ans = - 10 ** 9 NEW_LINE cn0 = 0 NEW_LINE cn1 = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT if ( cn1 > 0 ) : NEW_LINE INDENT cn1 -= 1 NEW_LINE DEDENT cn0 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( cn0 > 0 ) : NEW_LINE INDENT cn0 -= 1 NEW_LINE DEDENT cn1 += 1 NEW_LINE DEDENT ans = max ( [ ans , cn0 , cn1 ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "010101" NEW_LINE minOpsToEmptyString ( S ) NEW_LINE DEDENT