Program to find length of longest balanced subsequence in Python


Suppose we have a string s containing brackets parenthesis "(" and ")", we have to find the length of the longest subsequence of balanced brackets.

So, if the input is like s = "())(()(", then the output will be 4, as we can take the subsequence like "()()"

To solve this, we will follow these steps −

  • res := 0

  • n := size of s

  • close := 0

  • for i in range n - 1 to 0, decrease by 1, do

    • if s[i] is same as ")", then

      • close := close + 1

    • otherwise,

      • if close > 0, then

        • close := close - 1

        • res := res + 2

  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s):
      res = 0
      n = len(s)
      close = 0
      for i in range(n - 1, -1, -1):
         if s[i] == ")":
            close += 1
         else:
            if close > 0:
               close -= 1
                  res += 2
            return res
ob = Solution()
s = "())(()("
print(ob.solve(s))

Input

"())(()("

Output

4

Updated on: 10-Oct-2020

250 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements