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)
- Maximum length of consecutive 1's in a binary string in Python using Map function
- Length of the longest substring with no consecutive same letters
- Generate a Binary String without any consecutive 0's and at most K consecutive 1's
- Find the number of binary strings of length N with at least 3 consecutive 1s
- Find consecutive 1s of length >= n in binary representation of a number
- Find length of longest subsequence of one string which is substring of another string
- Count of Binary strings of length N having atmost M consecutive 1s or 0s alternatively exactly K times
- Length of longest connected 1’s in a Binary Grid
- Length of Longest sub-string that can be removed
- Length of longest palindromic sub-string : Recursion
- Check if a binary string contains consecutive same or not
- Longest sub string of 0's in a binary string which is repeated K times
- Check if a binary string has two consecutive occurrences of one everywhere
- Maximum Consecutive Zeroes in Concatenated Binary String
- Binary string with given frequencies of sums of consecutive pairs of characters
- Longest sub-sequence of a binary string divisible by 3
- Longest subsequence of the form 0*1*0* in a binary string
- Count of binary strings of length N with even set bit count and at most K consecutive 1s
- Check if a binary string contains all permutations of length k
- Binary String of given length that without a palindrome of size 3