# Program to find length of longest balanced subsequence in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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