
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find longest number of 1s after swapping one pair of bits in Python
Suppose we have a binary string s. If we can swap at most one pair of characters in the string, we have to find the resulting length of the longest contiguous substring of 1s.
So, if the input is like s = "1111011111", then the output will be 9, as we can swap s[4] and s[9] to get 9 consecutive 1s.
To solve this, we will follow these steps −
- l := 0, cnt := 0, ans := 0
- for r in range 0 to size of s, do
- cnt := cnt + (1 when s[r] is same as "0" otherwise 0)
- if cnt > 1, then
- cnt := cnt - (1 when s[l] is same as "0" otherwise 0)
- l := l + 1
- ans := maximum of ans and (r - l + 1)
- return minimum of ans and occurrence of 1 in s
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s): l = 0 cnt = 0 ans = 0 for r in range(len(s)): cnt += s[r] == "0" if cnt > 1: cnt -= s[l] == "0" l += 1 ans = max(ans, r - l + 1) return min(ans, s.count("1")) ob = Solution() s = "1111011111" print(ob.solve(s))
Input
"1111011111"
Output
9
- Related Articles
- Program to find longest subarray of 1s after deleting one element using Python
- Program to find length of longest set of 1s by flipping k bits in Python
- Program to find length of longest substring with 1s in a binary string after one 0-flip in Python
- Program to find longest distance of 1s in binary form of a number using Python
- Program to find remainder after dividing n number of 1s by m in Python
- Program to maximize the number of equivalent pairs after swapping in Python
- Program to find longest consecutive run of 1s in binary form of n in Python
- C++ Program to Swapping Pair of Characters
- Golang program to swapping pair of characters
- Program to find number of substrings with only 1s using Python
- Program to find length of longest palindromic substring after single rotation in Python
- Program to check all 1s are present one after another or not in Python
- Program to find length of longest contiguously strictly increasing sublist after removal in Python
- Program to find longest equivalent sublist after K increments in Python
- Program to find shortest string after removing different adjacent bits in Python

Advertisements