In this HackerEarth Largest Balanced String problem solution An empty sequence is balanced.
- A sequence of the form (A) or [A] or {A} is balanced if A is balanced.
- A sequence of the form AB is balanced if A and B both are balanced.
You are given a string A, consisting of ‘(‘, ‘)’, ‘[‘, ‘]’, ‘{‘ and ‘}’ only. You have to find the maximum length of the balanced string after performing some valid operation(s). Valid operations are
- Remove any character from string A
- Swap any two adjacent characters of string A
You can perform these valid operations in any order and any numbers of times.
HackerEarth Largest Balanced String problem solution.
#include <bits/stdc++.h>
using namespace std;
#define MAXN 100005
int main(int argc , char *args[]){
freopen(args[1], "r", stdin);
freopen(args[2], "w", stdout);
int tc;
cin >> tc;
while(tc--){
int cnt[200]={0};
string str;
cin >> str;
for(int i =0 ; i < str.size() ; i ++){
cnt[str[i]]++;
}
long long ans =0 ;
ans += 2*min(cnt['('],cnt[')']);
ans += 2*min(cnt['['],cnt[']']);
ans += 2*min(cnt['{'],cnt['}']);
cout <<ans <<"n";
}
return 0;
}
Second solution
#include<bits/stdc++.h>
using namespace std;
int solve (string str) {
map<char,int>mp;
/*cout<<str<<"n";
cout<<mp['{'];*/
for(int i=0;i<str.size();i++)
{
mp[str[i]]++;
}
int ans=0;
ans+=min(mp['('],mp[')'])*2;
ans+=min(mp['{'],mp['}'])*2;
ans+=min(mp['['],mp[']'])*2;
return ans;
// Write your code here
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int T;
cin >> T;
for(int t_i=0; t_i<T; t_i++)
{
string str;
cin>>str;
//getline(cin, str);
int out_;
out_ = solve(str);
cout << out_;
cout << "n";
}
}