Is there an easier method to solve this?

I came across the editorial of but found it a bit complex. So, Is there any easier method to solve this using C++?

Here is my solution in c++. It is kind of same as in editorial. but instead of removing you just consider the characters which you want in the final string and check for the conditions given in problem statement.

#include <bits/stdc++.h>

using namespace std;

int maxLen(string s){
    vector<char> chars;
    for(int i=0; s[i]; i++){
        if(find(chars.begin(), chars.end(), s[i]) == chars.end()){
    int max = 0;
    for(int i=0; i<chars.size(); i++){
        char a = chars[i];
        for(int j=i+1; j<chars.size(); j++){
            char b=chars[j];
            char lastchar = '\0';
            int len = 0;
            for(int k=0;s[k];k++){
                if(s[k]==a || s[k]==b){
                        len = 0;
                    lastchar = s[k];
            max = (max>len)?max:len;
    return max;

int main() {
    int n;
    cin >> n;
    string s;
    cin >> s;
    int result = maxLen(s);
    cout << result << endl;
    return 0;

1 Like