Given binary string str, the task is to find the minimum number of flips required to keep all 1s together in the given binary string, i.e. there must not be any 0 between 1s in the string.
Input: str = “0011111100”
Explanation: We dont need to flip any bits because all the ones are grouped together and there is no zero between any two ones.
Input: str = “11100111000101”
Explanation: We can flip the 4th and 5th bit to make them 1 and flip 12th and 14th bit to make them 0. So the resulting string is “11111111000000” with 4 possible flips.
Approach: To solve the problem mentioned above we will implement the dynamic programming approach where we will have the following states:
- The first state is dp[i] which signifies the number of flips required to make all zeroes up to the ith bit.
- Second state dp[i] which signifies the number of flips required to make the current bit 1 such that the conditions given in the question are satisfied.
So the required answer will be minimum flips for making the current bit 1 + minimum flips for making all bits after the current bit 0 for all values of i. But if all the bits in the given string are 0 then we don’t have to change anything, so we can check the minimum between our answer and the number of flips required to make the string with all zeroes. So we can compute the answer by iterating over all the characters in the string where,
answer = min ( answer, dp[i] + dp[n-1] – dp[i])
dp[i] = Minimum number of flips to set current bit to 1
dp[n-1] – dp[i] = Minimum number of flips required to make all bits after i as 0
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.