In this HackerEarth Super balanced bracket problem solution you are provided a balanced bracket sequence S. A super balanced bracket is a balanced bracket sequence that has the following structure:
((((.....))))

Here, all the opening brackets must contain corresponding closing brackets and all opening brackets must appear before any closing brackets. For example, (()) and ((())) are super balanced sequence but ()() and (()()) are not the super balanced sequence because there exists an opening bracket that appears after a closing bracket.

Your task is to determine the size of the largest super balanced bracket subsequence that is formed over all subsequences of the original sequence.


HackerEarth Super balanced bracket problem solution


HackerEarth Super balanced bracket problem solution.

#include <bits/stdc++.h>

typedef long double ld ;
#define long long long int
using namespace std;
#define mp make_pair
#define pb push_back
#define x first
#define y second
typedef pair<long,long> pll; 

const int N=1e5+1;
int arr[N];

void check_balance(string &s)
{
  int coun=0;
  int x=s.length();

  for(int i=0;i<x;i++)
  {
    if(s[i]=='(')
      coun++;
    else
      coun--;
    assert(coun>=0);
  }
  assert(coun==0);
}

int main()
{
  ios::sync_with_stdio(false);cin.tie(0);
  srand(time(NULL));

  // clock_t clk = clock();

  int t=1;
  cin>>t;
  while(t--)
  {
    string s;
    cin>>s;

    int x=s.length();
    // cout<<x<<endl;
    assert(1<=x && x<N);
    check_balance(s);
    arr[x]=0;

    for(int i=x-1;i>=0;i--)
      arr[i]=arr[i+1]+(s[i]==')');

    int coun=0;
    for(int i=0;i<x;i++)
    {
      if(s[i]=='(' && coun+1<=arr[i+1])
        coun++;
    }

    cout<<2*coun<<"\n";

    // clk = clock() - clk;
    // cout << "Time Elapsed: " << fixed << setprecision(10) << ((double)clk)/CLOCKS_PER_SEC << "\n";
  }

  return 0;
}



Second solution

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 5e5 + 14;

int main(){
  ios::sync_with_stdio(0), cin.tie(0);
  int t;
  cin >> t;
  while(t--){
    string s;
    cin >> s;
    int o = 0, cl = count(s.begin(), s.end(), ')'), ans = 0;
    for(auto c : s)
      if(c == '(')
        ans = max(ans, min(++o, cl) * 2);
      else
        cl--;
    cout << ans << '\n';
  }
}