Make a given Binary String non | Function to return the length of smallest subsequence required to be removed to make the given string non - decreasing ; Length of the string ; Count of zeros and ones ; Traverse the string ; Count minimum removals to obtain strings of the form "00000 . . . . " or "11111 . . . " ; Increment count ; Remove 1 s and remaining 0 s ; Driver Code
def min_length ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE total_zeros = 0 NEW_LINE total_ones = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT total_zeros += 1 NEW_LINE DEDENT else : NEW_LINE INDENT total_ones += 1 NEW_LINE DEDENT DEDENT ans = min ( total_zeros , total_ones ) NEW_LINE cur_zeros = 0 NEW_LINE cur_ones = 0 NEW_LINE for x in str : NEW_LINE INDENT if ( x == '0' ) : NEW_LINE INDENT cur_zeros += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cur_ones += 1 NEW_LINE DEDENT ans = min ( ans , cur_ones + ( total_zeros - cur_zeros ) ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "10011" NEW_LINE min_length ( str ) NEW_LINE DEDENT