Maximum length of a substring required to be flipped repeatedly to make all characters of binary string equal to 0
Given a binary string S, the task is to find the maximum length of substrings required to be flipped repeatedly to make all the characters of a binary string equal to ‘0’.
Input: S = “010”
Following are the order of flipping of substring of at least K for the value of K as 2:
- Flip the substring S[0, 2] of length 3(>= K) modifies the string S to “101”.
- Flip the substring S[0, 1] of length 2(>= K) modifies the string S to “011”.
- Flip the substring S[1, 2] of length 2(>= K) modifies the string S to “000”.
For the value of K as 2(which is the maximum possible value) all the characters of the string can be made 0. Therefore, print 2.
Input: S = “00001111”
Approach: The given problem can be solved by traversing the given string S, now if at any point the adjacent characters are not the same then flip one sub-string LHS or RHS. For that, take the maximum length of LHS and RHS. There can be multiple adjacent places where characters are not equal. For each pair of substrings, the maximum required will be different. Now to change all the characters to ‘0’ take the minimum among all those maximums. Follow the steps below to solve the problem:
- Initialize the variable, say ans as N that stores the maximum possible value of K.
- Iterate over the range [0, N – 1) using the variable i and perform the following steps:
- If the value of s[i] and s[i + 1] are not the same, then update the value of ans to the minimum of ans or maximum of (i + 1) or (N – i – 1).
- After performing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Please Login to comment...