Maximum length of consecutive 1s or 0s after flipping at most K characters
Given a binary string S of size N and an integer K, the task is to find the maximum length of consecutive 1s or 0s after flipping at most K characters of the given binary string S.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: S = “1001”, K = 1
Flip the K(= 1) characters at index 3 of the string modifies the string S to “1000”. Now the maximum length of consecutive 0s is 3, which is the required result.
Input: S = “11011011”, K = 3
- Initialize a function, say maxLength(S, N, ch, K) that find the maximum length of characters ch after flipping at most K characters using the following steps:
- Initialize a variable, say cnt that stores the count of character ch in the window.
- Initialize a variable, say left that stores the starting of the resultant window.
- Initialize a variable, say ans that stores the resultant length of consecutive K characters as ch after at most K flips.
- Traverse the string S using the variable right and perform the following steps:
- If the value of S[right] is ch, then increment the value of cnt by 1.
- Iterate until the value of cnt is greater than K, then increment the left pointer and decrement the value of cnt by 1.
- Update the value of ans to maximum of ans and (right – left + 1).
- After completing the above steps, print the maximum of the value returned by the maxLength(S, N, ‘0’, K) and maxLength(S, N, ‘1’, K) as the result.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)