- 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 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

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

- Related Articles
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic subsequence in Python
- Program to find length of longest fibonacci subsequence in Python
- Program to find length of longest circular increasing subsequence in python
- Program to find length of longest common subsequence of three strings in Python
- Program to find length of longest bitonic subsequence in C++
- Program to find length of longest common subsequence in C++
- Program to find out the length of longest palindromic subsequence using Python
- Program to find length of longest arithmetic subsequence with constant difference in Python
- Program to find length of longest arithmetic subsequence of a given list in Python
- Program to find length of longest Fibonacci subsequence from a given list in Python
- Program to find length of longest alternating subsequence from a given list in Python
- Program to find length of longest sign alternating subsequence from a list of numbers in Python
- Program to find length of longest increasing subsequence with at least k odd values in Python

Advertisements