Maximum length of balanced string after swapping and removal of characters | PHP implementation of the approach Function to return the length of the longest balanced sub - string ; To store the count of parentheses ; Traversing the string ; Check type of parentheses and incrementing count for it ; Sum all pair of balanced parentheses ; Driven code
< ? php function maxBalancedStr ( $ s ) { $ open1 = 0 ; $ close1 = 0 ; $ open2 = 0 ; $ close2 = 0 ; $ open3 = 0 ; $ close3 = 0 ; for ( $ i = 0 ; $ i < strlen ( $ s ) ; $ i ++ ) { switch ( $ s [ $ i ] ) { case ' ( ' : $ open1 ++ ; break ; case ' ) ' : $ close1 ++ ; break ; case ' { ' : $ open2 ++ ; break ; case ' } ' : $ close2 ++ ; break ; case ' [ ' : $ open3 ++ ; break ; case ' ] ' : $ close3 ++ ; break ; } } $ maxLen = 2 * min ( $ open1 , $ close1 ) + 2 * min ( $ open2 , $ close2 ) + 2 * min ( $ open3 , $ close3 ) ; return $ maxLen ; } { $ s = " ) ) [ ] ] ( ( " ; echo ( maxBalancedStr ( $ s ) ) ; }