# Will anyone pls explain me these 4 lines 17 to 21

``````#include<bits/stdc++.h>
using namespace std;
#define ll long long
int t, n;
string s;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> t;
while (t--) {
cin >> n >> s;
int sm = 0;
vector<int> mp((n << 1) + 1, -1);
int res = 0;
for (int i = 0; i < n; i++) {
sm += (s[i] == 'c') ? 1 : -1;
if (sm == 0) {
res = i + 1;
}
if (mp[sm + n] == -1) {
mp[sm + n] = i;
continue;
}
res = max(res, i - mp[sm + n]);
}
cout << res << endl;
}return 0;
}
``````

I am not able to understand your code but I solved with same logic so you can see my code and check for error.

#include <bits/stdc++.h>
using namespace std;
int main() {
// freopen(“input.txt”,“r”,stdin);
// freopen(“output.txt”,“w”,stdout);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while(t–) {
ll n;
cin>>n;
string S;
char s[n];
cin>>S;
for(ll i=0;i<n;i++) {
if(S[i] == ‘c’) s[i]=‘1’;
else s[i] = ‘0’;
}
map<ll,ll> m;
ll sum= 0;
ll maxsizesofar = 0;
for(ll i=0;i<n;i++) {
if(s[i] == ‘0’) sum-=1;
else sum += 1;
if(sum==0) maxsizesofar = i+1;
if(m.find(sum) != m.end()) maxsizesofar = max(maxsizesofar,i-m[sum]);
else m[sum]=i;
}
cout<<maxsizesofar<<endl;
}
return 0 ;

}

thanx for replying brother but i was just asking for logic (explanation behind writing that code ) pls explain me in your code started from maxsizesofar=i+1

MP[sm+n] denotes that for the first time where sm came , n is added for padding as sm can be negative

1 Like