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.
Input : S = "()())" Output : 4 ()() is the longest balanced subsequence of length 4. Input : s = "()(((((()" Output : 4
A brute force approach is to find all subsequence of the given string S and check for all possible subsequence if it form a balanced sequence, if yes, compare it with maximum value.
The better approach is to use Dynamic Programming.
Longest Balananced 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[length of string - 1] (considering 0 indexing) will be our answer.
Below is the implementation of this approach:
Time Complexity : O(n2)
Auxiliary Space : O(n2)
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
- Balanced expression with replacement
- Common characters in n strings
- Tile Stacking Problem
- Counting pairs when a person can form pair with at most one
- Count of strings where adjacent characters are of difference one
- Longest Repeated Subsequence
- Longest alternating sub-array starting from every index in a Binary Array
- Longest Common Subsequence with at most k changes allowed
- Non-decreasing subsequence of size k with minimum sum
- Find all distinct subset (or subsequence) sums of an array
- Print all longest common sub-sequences in lexicographical order
- Minimum number of bracket reversals needed to make an expression balanced
- Length of the longest valid substring
- Weighted Job Scheduling
- Longest Common Subsequence | DP-4
Improved By : vt_m