Minimum flips to make all 1s in left and 0s in right in C++

C++Server Side ProgrammingProgramming

Problem statement

Given a binary string in which we can flip all 1’s in left part and all 0’s in right part. The task is to calculate minimum flips required to make all 1’s in left and all 0’s in right

Example

Given binary string is 0010101. In this string there are 3 1-bits and 4 0-bits. We have to flip highlighted 4 bits to make all 1’s in left and all 0’s in right as shown below −

0010101

After flipping string will become −

1110000

Algorithm

  • Traverse the string from left to right and calculate the number of flips required to convert all 0’s to 1’s.
  • Traverse the string from right to left and calculate the number of flips required to covert all 1’s to 0’s
  • Traverse through all positions between bits and find minimal value of (0’s flips + 1′s flips)

Example

#include <iostream>
#include <string>
#include <climits>
using namespace std;
int minFlips(string binaryString) {
   int n = binaryString.length();
   int flipCnt, zeroFlips[n], oneFlips[n];
   flipCnt = 0;
   for (int i = 0; i < n; ++i) {
      if (binaryString[i] == '0') {
         ++flipCnt;
      }
      zeroFlips[i] = flipCnt;
   }
   flipCnt = 0;
   for (int i = n - 1; i >= 0; --i) {
      if (binaryString[i] == '1') {
         ++flipCnt;
      }
      oneFlips[i] = flipCnt;
   }
   int minFlips = INT_MAX;
   for (int i = 1; i < n; ++i) {
      int sum = zeroFlips[i - 1] + oneFlips[i]; if (sum < minFlips) {
         minFlips = sum;
      }
   }
   return minFlips;
}
int main() {
   string binaryString = "0010101";
   cout << "Minimum flips: " << minFlips(binaryString) <<
   endl;
   return 0;
}

Output

When you compile and execute above program. It generates following output −

Minimum flips: 4
raja
Published on 22-Nov-2019 09:52:05
Advertisements