Program to find longest number of 1s after swapping one pair of bits in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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
raja
Published on 19-Nov-2020 11:42:07
Advertisements