• + 1 comment

    I used a condition to check if the absolute difference between the counts of the chosen characters is at most 1, which is the case with valid t's. That would make the code quite faster if we had very large strings.

    from collections import Counter
    from itertools import combinations
    
    s_len = int(raw_input().strip())
    s = raw_input().strip()
    
    C = Counter(s)
    max_len = 0
    for (c1, c2) in combinations(set(s), 2):
        if abs(C[c1] - C[c2]) <= 1:
            t = [c for c in s if c in {c1, c2}]
            if all(t[j] != t[j-1] for j in range(1, len(t))):
                max_len = max(max_len, len(t))
    
    print max_len