Minimum cost of flipping characters required to convert Binary String to 0 s only | Function to find the minimum cost to convert given string to 0 s only ; Length of string ; Stores the index of leftmost '1' in str ; Update the index of leftmost '1' in str ; Stores the index of rightmost '1' in str ; Update the index of rightmost '1' in str ; If str does not contain any '1' s ; No changes required ; Stores minimum cost ; Iterating through str form left_1 to right_1 ; Stores length of consecutive 0 s ; Calculate length of consecutive 0 s ; If a substring of 0 s exists ; Update minimum cost ; Printing the minimum cost ; Driver Code
def convert_to_allzeroes ( st , a , b ) : NEW_LINE INDENT length = len ( st ) NEW_LINE left_1 = 0 NEW_LINE i = 0 NEW_LINE while ( i < length and st [ i ] == '0' ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT left_1 = i NEW_LINE right_1 = 0 NEW_LINE i = length - 1 NEW_LINE while ( i >= 0 and st [ i ] == '0' ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT right_1 = i NEW_LINE if ( left_1 == length and right_1 == - 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT cost = a NEW_LINE for i in range ( left_1 , right_1 + 1 ) : NEW_LINE INDENT zeroes = 0 NEW_LINE while ( i < length and st [ i ] == '0' ) : NEW_LINE INDENT zeroes += 1 NEW_LINE i += 1 NEW_LINE DEDENT if ( zeroes ) : NEW_LINE INDENT cost += min ( zeroes * b , a ) NEW_LINE DEDENT DEDENT print ( cost ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = "01101110" NEW_LINE A = 5 NEW_LINE B = 1 NEW_LINE convert_to_allzeroes ( st , A , B ) NEW_LINE DEDENT