Skip to content
Related Articles

Related Articles

Length of Longest Balanced Subsequence
  • Difficulty Level : Medium
  • Last Updated : 04 May, 2021

Given a string S, find the length of longest balanced subsequence in it. A balanced string is defined as:- 
 

  • A Null string is a balanced string.
  • If X and Y are balanced strings, then (X)Y and XY are balanced strings.

Examples : 
 

Input : S = "()())"
Output : 4

()() is the longest balanced subsequence 
of length 4.

Input : s = "()(((((()"
Output : 4

 

Approach 1: A brute force approach is to find all subsequences of the given string S and check for all possible subsequences if they form a balanced sequence, if yes, compare it with maximum value.
The better approach is to use Dynamic Programming
Longest Balanced Subsequence (LBS), can be recursively defined as below.
 

LBS of substring str[i..j] : 
If str[i] == str[j]
    LBS(str, i, j) = LBS(str, i + 1, j - 1) + 2
Else
    LBS(str, i, j) = max(LBS(str, i, k) +
                         LBS(str, k + 1, j))
                     Where i <= k < j   

Declare a 2D matrix dp[][], where our state dp[i][j] will denote the length of longest balanced subsequence from index i to j. We will compute this state in order of increasing j – i. For a particular state dp[i][j], we will try to match the jth symbol with kth symbol, that can be done only if S[k] is ‘(‘ and S[j] is ‘)’, we will take the max of 2 + dp[i][k – 1] + dp[k + 1][j – 1] for all such possible k and also max(dp[i + 1][j], dp[i][j – 1]) and put the value in dp[i][j]. In this way we can fill all the dp states. dp[0][length of string – 1] (considering 0 indexing) will be our answer.
Below is the implementation of this approach: 
 



C++




// C++ program to find length of
// the longest balanced subsequence
#include <bits/stdc++.h>
using namespace std;
  
int maxLength(char s[], int n)
{
    int dp[n][n];
    memset(dp, 0, sizeof(dp));
  
    // Considering all balanced
    // substrings of length 2
    for (int i = 0; i < n - 1; i++)
        if (s[i] == '(' && s[i + 1] == ')')
            dp[i][i + 1] = 2;
  
    // Considering all other substrings
    for (int l = 2; l < n; l++) {
        for (int i = 0, j = l; j < n; i++, j++) {
            if (s[i] == '(' && s[j] == ')')
                dp[i][j] = 2 + dp[i + 1][j - 1];
  
            for (int k = i; k < j; k++)
                dp[i][j] = max(dp[i][j],
                               dp[i][k] + dp[k + 1][j]);
        }
    }
  
    return dp[0][n - 1];
}
  
// Driver Code
int main()
{
    char s[] = "()(((((()";
    int n = strlen(s);
    cout << maxLength(s, n) << endl;
    return 0;
}

Java




// Java program to find length of the
// longest balanced subsequence.
import java.io.*;
  
class GFG {
    static int maxLength(String s, int n)
    {
        int dp[][] = new int[n][n];
  
        // Considering all balanced substrings
        // of length 2
        for (int i = 0; i < n - 1; i++)
            if (s.charAt(i) == '(' && s.charAt(i + 1) == ')')
                dp[i][i + 1] = 2;
  
        // Considering all other substrings
        for (int l = 2; l < n; l++) {
            for (int i = 0, j = l; j < n; i++, j++) {
                if (s.charAt(i) == '(' && s.charAt(j) == ')')
                    dp[i][j] = 2 + dp[i + 1][j - 1];
  
                for (int k = i; k < j; k++)
                    dp[i][j] = Math.max(dp[i][j],
                                        dp[i][k] + dp[k + 1][j]);
            }
        }
  
        return dp[0][n - 1];
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        String s = "()(((((()";
        int n = s.length();
        System.out.println(maxLength(s, n));
    }
}
// This code is contributed by Prerna Saini

Python3




# Python3 program to find length of 
# the longest balanced subsequence 
  
def maxLength(s, n):
      
    dp = [[0 for i in range(n)]
             for i in range(n)]
               
    # Considering all balanced 
    # substrings of length 2 
    for i in range(n - 1): 
        if (s[i] == '(' and s[i + 1] == ')'): 
            dp[i][i + 1] = 2
  
    # Considering all other substrings 
    for l in range(2, n):
        i = -1
        for j in range(l, n):
            i += 1
            if (s[i] == '(' and s[j] == ')'): 
                dp[i][j] = 2 + dp[i + 1][j - 1
            for k in range(i, j): 
                dp[i][j] = max(dp[i][j], dp[i][k] +
                                         dp[k + 1][j])
    return dp[0][n - 1
  
# Driver Code 
s = "()(((((()"
n = len(s)
print(maxLength(s, n)) 
  
# This code is contributed 
# by sahishelangia

C#




// C# program to find length of the
// longest balanced subsequence.
using System;
  
class GFG {
  
    static int maxLength(String s, int n)
    {
        int[, ] dp = new int[n, n];
  
        // Considering all balanced substrings
        // of length 2
        for (int i = 0; i < n - 1; i++)
            if (s[i] == '(' && s[i + 1] == ')')
                dp[i, i + 1] = 2;
  
        // Considering all other substrings
        for (int l = 2; l < n; l++) {
            for (int i = 0, j = l; j < n; i++, j++) {
                if (s[i] == '(' && s[j] == ')')
                    dp[i, j] = 2 + dp[i + 1, j - 1];
  
                for (int k = i; k < j; k++)
                    dp[i, j] = Math.Max(dp[i, j],
                                        dp[i, k] + dp[k + 1, j]);
            }
        }
  
        return dp[0, n - 1];
    }
  
    // Driver Code
    public static void Main()
    {
        string s = "()(((((()";
        int n = s.Length;
        Console.WriteLine(maxLength(s, n));
    }
}
  
// This code is contributed by vt_m.

PHP




<?php 
// PHP program to find length of 
// the longest balanced subsequence
function maxLength($s, $n)
{
    $dp = array_fill(0, $n,
          array_fill(0, $n, NULL)); 
  
    // Considering all balanced 
    // substrings of length 2
    for ($i = 0; $i < $n - 1; $i++)
        if ($s[$i] == '(' && $s[$i + 1] == ')')
            $dp[$i][$i + 1] = 2;
  
    // Considering all other substrings
    for ($l = 2; $l < $n; $l++) 
    {
        for ($i = 0, $j = $l; $j < $n; $i++, $j++) 
        {
            if ($s[$i] == '(' && $s[$j] == ')')
                $dp[$i][$j] = 2 + $dp[$i + 1][$j - 1];
  
            for ($k = $i; $k < $j; $k++) 
                $dp[$i][$j] = max($dp[$i][$j],
                                  $dp[$i][$k] + 
                                  $dp[$k + 1][$j]);         
        }
    }
  
    return $dp[0][$n - 1];
}
  
// Driver Code
$s = "()(((((()";
$n = strlen($s);
echo maxLength($s, $n)."\n";
  
// This code is contributed by ita_c
?>
Output: 
4

 

Time Complexity : O(n2
Auxiliary Space : O(n2)
Approach 2: This approach solves the problem in a more efficient manner.
 

  1. Count number of braces to be removed to get the longest balanced parentheses sub-sequence.
  2. If at ith index number of close braces is greater than the number of open braces then that close brace has to be removed.
  3. Count number of close braces that need to be removed.
  4. In the end, the number of extra open braces is also to be removed.
  5. So total count to be removed would be the sum of extra open braces and invalid close braces.

 

C++




// C++ program to find length of
// the longest balanced subsequence
#include <bits/stdc++.h>
using namespace std;
  
int maxLength(char s[], int n)
{
    // As it's subsequence - assuming first
    // open brace would map to a first close
    // brace which occurs after the open brace
    // to make subsequence balanced and second
    // open brace would map to second close
    // brace and so on.
  
    // Variable to count all the open brace
    // that does not have the corresponding
    // closing brace.
    int invalidOpenBraces = 0;
  
    // To count all the close brace that
    // does not have the corresponding open brace.
    int invalidCloseBraces = 0;
  
    // Iterating over the String
    for (int i = 0; i < n; i++) {
        if (s[i] == '(') {
  
            // Number of open braces that
            // hasn't been closed yet.
            invalidOpenBraces++;
        }
        else {
            if (invalidOpenBraces == 0) {
  
                // Number of close braces that
                // cannot be mapped to any open
                // brace.
                invalidCloseBraces++;
            }
            else {
  
                // Mapping the ith close brace
                // to one of the open brace.
                invalidOpenBraces--;
            }
        }
    }
    return (
        n - (invalidOpenBraces
             + invalidCloseBraces));
}
  
// Driver Code
int main()
{
    char s[] = "()(((((()";
    int n = strlen(s);
    cout << maxLength(s, n) << endl;
    return 0;
}

Java




// Java program to find the length of the
// longest balanced subsequence.
import java.io.*;
  
class GFG {
    static int maxLength(String s, int n)
    {
        // As it's subsequence - assuming first
        // open brace would map to a first close
        // brace which occurs after the open brace
        // to make subsequence balanced and second
        // open brace would map to second close
        // brace and so on.
  
        // Variable to count all the open brace
        // that does not have the corresponding
        // closing brace.
        int invalidOpenBraces = 0;
  
        // To count all the close brace that
        // does not have the corresponding open brace.
        int invalidCloseBraces = 0;
  
        // Iterating over the String
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == '(') {
  
                // Number of open braces that
                // hasn't been closed yet.vvvvvv
                invalidOpenBraces++;
            }
            else {
                if (invalidOpenBraces == 0) {
  
                    // Number of close braces that
                    // cannot be mapped to any open
                    // brace.
                    invalidCloseBraces++;
                }
                else {
  
                    // Mapping the ith close brace
                    // to one of the open brace.
                    invalidOpenBraces--;
                }
            }
        }
        return (
            n - (invalidOpenBraces
                 + invalidCloseBraces));
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        String s = "()(((((()";
        int n = s.length();
        System.out.println(maxLength(s, n));
    }
}

Python3




# Python3 program to find length of 
# the longest balanced subsequence 
  
def maxLength(s, n):
              
    # As it's subsequence - assuming first
    # open brace would map to a first close
    # brace which occurs after the open brace
    # to make subsequence balanced and second
    # open brace would map to second close 
    # brace and so on.
      
    # Variable to count all the open brace 
    # that does not have the corresponding 
    # closing brace. 
    invalidOpenBraces = 0;
  
    # To count all the close brace that does
    # not have the corresponding open brace.
    invalidCloseBraces = 0;
      
    # Iterating over the String
    for i in range(n):
        if( s[i] == '(' ):
                  
                # Number of open braces that 
                # hasn't been closed yet.
                invalidOpenBraces += 1
        else:
            if(invalidOpenBraces == 0):
                # Number of close braces that
                # cannot be mapped to any open
                # brace.
                invalidCloseBraces += 1
            else:
                # Mapping the ith close brace
                # to one of the open brace.
                invalidOpenBraces -= 1
  
    return (
n - (
invalidOpenBraces + invalidCloseBraces)) 
  
# Driver Code 
s = "()(((((()"
n = len(s)
print(maxLength(s, n))

C#




// C# program to find length of the
// longest balanced subsequence.
using System;
  
class GFG {
  
    static int maxLength(String s, int n)
    {
  
        // As it's subsequence - assuming first
        // open brace would map to a first close
        // brace which occurs after the open brace
        // to make subsequence balanced and second
        // open brace would map to second close
        // brace and so on.
  
        // Variable to count all the open brace
        // that does not have the corresponding
        // closing brace.
        int invalidOpenBraces = 0;
  
        // To count all the close brace that
        // does not have the corresponding open brace.
        int invalidCloseBraces = 0;
  
        // Iterating over the String
        for (int i = 0; i < n; i++) {
            if (s[i] == '(') {
  
                // Number of open braces that
                // hasn't been closed yet.
                invalidOpenBraces++;
            }
            else {
                if (invalidOpenBraces == 0) {
  
                    // Number of close braces that
                    // cannot be mapped to any open brace.
                    invalidCloseBraces++;
                }
                else {
  
                    // Mapping the ith close brace to
                    // one of the open brace.
                    invalidOpenBraces--;
                }
            }
        }
        return (
            n - (invalidOpenBraces
                 + invalidCloseBraces));
    }
  
    // Driver Code
    public static void Main()
    {
        string s = "()(((((()";
        int n = s.Length;
        Console.WriteLine(maxLength(s, n));
    }
}

Javascript




<script>
  
// Javascript program to find the length of the
// longest balanced subsequence.
    
    function maxLength(s, n)
    {
        // As it's subsequence - assuming first
        // open brace would map to a first close
        // brace which occurs after the open brace
        // to make subsequence balanced and second
        // open brace would map to second close
        // brace and so on.
    
        // Variable to count all the open brace
        // that does not have the corresponding
        // closing brace.
        let invalidOpenBraces = 0;
    
        // To count all the close brace that
        // does not have the corresponding open brace.
        let invalidCloseBraces = 0;
    
        // Iterating over the String
        for (let i = 0; i < n; i++) {
            if (s[i] == '(') {
    
                // Number of open braces that
                // hasn't been closed yet.vvvvvv
                invalidOpenBraces++;
            }
            else {
                if (invalidOpenBraces == 0) {
    
                    // Number of close braces that
                    // cannot be mapped to any open
                    // brace.
                    invalidCloseBraces++;
                }
                else {
    
                    // Mapping the ith close brace
                    // to one of the open brace.
                    invalidOpenBraces--;
                }
            }
        }
        return (
            n - (invalidOpenBraces
                 + invalidCloseBraces));
    }
  
// driver program 
  
        let s = "()(((((()";
        let n = s.length;
        document.write(maxLength(s, n));
      
</script>
Output: 
4

 

Time Complexity : O(n) 
Auxiliary Space : O(1)
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

My Personal Notes arrow_drop_up
Recommended Articles
Page :