Minimize cost to convert all characters of a binary string to 0 s | Function to get the minimum Cost to convert all characters of given string to 0 s ; Stores the range of indexes of characters that need to be flipped ; Stores the number of times current character is flipped ; Stores minimum cost to get the required string ; Traverse the given string ; Remove all value from pq whose value is less than i ; Update flip ; Get the current number ; If current character is flipped odd times ; If current character contains non - zero value ; Update flip ; Update cost ; Append R [ i ] into pq ; Driver code ; Function call
def minCost ( s , R , C , N ) : NEW_LINE INDENT ch = list ( s ) NEW_LINE pq = [ ] NEW_LINE flip = 0 NEW_LINE cost = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT while ( len ( pq ) > 0 and pq [ 0 ] < i ) : NEW_LINE INDENT pq . pop ( 0 ) ; NEW_LINE flip -= 1 NEW_LINE DEDENT cn = ord ( ch [ i ] ) - ord ( '0' ) NEW_LINE if ( flip % 2 == 1 ) : NEW_LINE INDENT cn = 1 - cn NEW_LINE DEDENT if ( cn == 1 ) : NEW_LINE INDENT flip += 1 NEW_LINE cost += C [ i ] NEW_LINE pq . append ( R [ i ] ) NEW_LINE DEDENT DEDENT return cost NEW_LINE DEDENT N = 4 NEW_LINE s = "1010" NEW_LINE R = [ 1 , 2 , 2 , 3 ] NEW_LINE C = [ 3 , 1 , 2 , 3 ] NEW_LINE print ( minCost ( s , R , C , N ) ) NEW_LINE