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 ; Prleting the minimum cost ; Driver Code
function convert_to_allzeroes ( str , a , b ) { let len = str . length ; let left_1 , i = 0 ; while ( i < len && str [ i ] == ' ' ) i ++ ; left_1 = i ; let right_1 ; i = len - 1 ; while ( i >= 0 && str [ i ] == ' ' ) i -- ; right_1 = i ; if ( left_1 == len && right_1 == - 1 ) { document . write ( 0 ) ; return ; } let cost = a , zeroes ; for ( i = left_1 ; i <= right_1 ; i ++ ) { zeroes = 0 ; while ( i < len && str [ i ] == ' ' ) { zeroes ++ ; i ++ ; } if ( zeroes != 0 ) cost += Math . min ( zeroes * b , a ) ; } document . write ( cost ) ; } let str = " " ; let A = 5 , B = 1 ; convert_to_allzeroes ( str , A , B ) ;