- binary-string, Mathematical, Strings

Minimize cost of flipping or swaps to make a Binary String balanced

Minimize cost of flipping or swaps to make a Binary String balancedGiven a binary string S of size N(where N is even), the task is to find the minimum cost of making the given binary string balanced by flipping one of the adjacent different characters at the cost of 1 unit or swap the characters at indices i and j such that (i < j) at the cost of (j – i) unit. If it impossible to make the string balanced, the print “-1”.A binary string is balanced if it can be reduced to an empty string by deleting two consecutive alternating characters at once and then concatenating the remaining characters.Examples:Input: S = “110110”Output: 1Explanation: Following operations are performed:Operation 1: As the adjacent characters at indices 0 and 1 are different, flipping S[0] modifies S to “010110”. Cost = 1.After completing the above operations, the given string becomes balanced, as it can be reduced to an empty string by deleting two consecutive alternating characters.Therefore, the total cost is 1.Input: S = “11100”Output: -1Approach: The given problem can be solved based on the observations that the flipping of the adjacent different characters is more optimal than using the swapping of characters and the position of 0s and 1s in the string does not matter. Follow the steps below to solve the problem:Below is the implementation of the above approach:C++#include 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