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