
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements