Minimize cost of flipping or swaps to make a Binary String balanced | C ++ program for the above approach ; Function to find the minimum cost to convert the given string into balanced string ; Stores count of 1 ' s ▁ and ▁ 0' s in the string ; Traverse the string ; Increment count1 ; Increment count 0 ; Stores absolute difference of counts of 0 ' s ▁ and ▁ 1' s ; If string consists of only 0 ' s ▁ and ▁ 1' s ; Print minimum cost ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinimumCost ( string s , int N ) { int count_1 = 0 , count_0 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '1' ) count_1 ++ ; else count_0 ++ ; } int k = abs ( count_0 - count_1 ) ; if ( count_1 == N count_0 == N ) cout << -1 << endl ; else cout << k / 2 << endl ; } int main ( ) { string S = "110110" ; int N = S . length ( ) ; findMinimumCost ( S , N ) ; return 0 ; }