Minimize cost of flipping or swaps to make a Binary String balanced | Function to find the minimum cost to convert the given 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 consists of only 0 ' s ▁ and ▁ 1' s ; Print the minimum cost ; Driver Code
def findMinimumCost ( s , N ) : NEW_LINE INDENT count_1 , count_0 = 0 , 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT count_1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count_0 += 1 NEW_LINE DEDENT DEDENT k = abs ( count_0 - count_1 ) NEW_LINE if ( count_1 == N or count_0 == N ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( k // 2 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "110110" NEW_LINE N = len ( S ) NEW_LINE findMinimumCost ( S , N ) NEW_LINE DEDENT