Minimum cost of flipping characters required to convert Binary String to 0 s only | C ++ Program to implement the above approach ; 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
#include <iostream> NEW_LINE using namespace std ; void convert_to_allzeroes ( string str , int a , int b ) { int len = str . length ( ) ; int left_1 , i = 0 ; while ( i < len && str [ i ] == '0' ) i ++ ; left_1 = i ; int right_1 ; i = len - 1 ; while ( i >= 0 && str [ i ] == '0' ) i -- ; right_1 = i ; if ( left_1 == len && right_1 == -1 ) { cout << 0 ; return ; } int cost = a , zeroes ; for ( i = left_1 ; i <= right_1 ; i ++ ) { zeroes = 0 ; while ( i < len && str [ i ] == '0' ) { zeroes ++ ; i ++ ; } if ( zeroes ) cost += min ( zeroes * b , a ) ; } cout << cost ; } int main ( ) { string str = "01101110" ; int A = 5 , B = 1 ; convert_to_allzeroes ( str , A , B ) ; return 0 ; }