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 ; 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
function minCost ( str , N , R , C ) { str = str . split ( ' ' ) ; var pq = [ ] ; var flip = 0 ; var cost = 0 ; for ( var i = 0 ; i < N ; i ++ ) { while ( pq . length > 0 && pq [ pq . length - 1 ] < i ) { pq . pop ( ) ; flip -- ; } if ( flip % 2 == 1 ) { str [ i ] = String . fromCharCode ( ' ' . charCodeAt ( 0 ) - str [ i ] . charCodeAt ( 0 ) + ' ' . charCodeAt ( 0 ) ) ; } if ( str [ i ] == ' ' ) { flip ++ ; cost += C [ i ] ; pq . push ( R [ i ] ) ; } pq . sort ( ( a , b ) => b - a ) ; } return cost ; } var str = " " ; var R = [ 1 , 2 , 2 , 3 ] ; var C = [ 3 , 1 , 2 , 3 ] ; var N = str . length ; document . write ( minCost ( str , N , R , C ) ) ;