Given a Binary String of length . It is allowed to do at most one swap between any 0 and 1. The task is to find the length of the longest consecutive 1’s that can be achieved.
Input : str = "111011101" Output : 7 We can swap 0 at 4th with 1 at 10th position Input : str = "111000" Output : 3 We cannot obtain more than 3 1's after
- Count all 1’s in the array in a variable say cnt_one.
- Maintain two vectors or arrays storing cumulative ones from left and right.
- Whenever there is a 0:
- if (left[i-1]+right[i+1] < cnt_one) store max_count = left[i-1] + right [i+1] + 1, as by swapping we will get one extra one in place of 0.
- else max_count = left[i-1] + right[i+1].
- Output is the maximum value of max_count that can be achieved.
Below is the implementation of the above approach:
Time Complexity: O(N)
- Generate a Binary String without any consecutive 0's and at most K consecutive 1's
- Form the smallest number using at most one swap operation
- Count of binary strings of length N with even set bit count and at most K consecutive 1s
- Count possible binary strings of length N without P consecutive 0s and Q consecutive 1s
- Count of substrings of a binary string containing K ones
- Maximum difference of zeros and ones in binary string
- Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
- Find length of longest subsequence of one string which is substring of another string
- Check if a binary string has two consecutive occurrences of one everywhere
- Find length of longest substring with at most K normal characters
- Meta Strings (Check if two strings can become same after a swap in one string)
- Lexicographically largest string possible in one swap
- Length of the longest substring with no consecutive same letters
- Maximum length of consecutive 1's in a binary string in Python using Map function
- Largest lexicographical string with at most K consecutive elements
- Number of ones in the smallest repunit
- Move all zeros to start and ones to end in an Array of random integers
- Check whether two strings can be made equal by copying their characters with the adjacent ones
- Maximum number of strings that can be formed with given zeros and ones
- Length of the longest subsegment which is UpDown after inserting atmost one integer
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.