Given a string, remove characters until the string is made up of any two alternating characters.  When you choose a character to remove, all instances of that character must be removed.  Determine the longest string possible that contains just two alternating letters.

Example    

$s=\text{'abaacdabd'}$   

Delete a, to leave bcdbd.  Now, remove the character c to leave the valid string bdbd with a length of 4. Removing either b or d at any point would not result in a valid string.  Return $4$.   

Given a string $s$, convert it to the longest possible string $t$ made up only of alternating characters.  Return the length of string $t$.  If no string $t$ can be formed, return $0$.

Function Description

Complete the alternate function in the editor below.  

alternate has the following parameter(s):  

string s: a string   

Returns. 

int: the length of the longest valid string, or $0$ if there are none   

Input Format

The first line contains a single integer that denotes the length of $s$. 

The second line contains string $s$.

Constraints

$1\leq\text{length of}\text{ s}\leq1000$
$s[i]\in\operatorname{ascii[a-z]}$ 

Sample Input
STDIN       Function
-----       --------
10          length of s = 10
beabeefeab  s = 'beabeefeab'

Sample Output
5

Explanation

The characters present in $s$ are a, b, e, and f. This means that $t$ must consist of two of those characters and we must delete two others.  Our choices for characters to leave are [a,b], [a,e], [a, f], [b, e], [b, f] and [e, f].

If we delete e and f, the resulting string is babab. This is a valid $t$ as there are only two distinct characters (a and b), and they are alternating within the string.

If we delete a and f, the resulting string is bebeeeb. This is not a valid string $t$ because there are consecutive e's present.  Removing them would leave consecutive b's, so this fails to produce a valid string $t$.

Other cases are solved similarly.

babab is the longest string we can create.

Difficulty: EASY
Tags: String algorithms

Starter code:

Solutions:
def char_range(c1, c2):
	for c in range(ord(c1), ord(c2) + 1):
		yield chr(c)

def is_alternating(s):
	for i in range(len(s) - 1):
		if s[i] == s[i + 1]:
			return False
	return True
len_s = int(input())
s = input()
max_len = 0
for c1 in char_range('a', 'z'):
	for c2 in char_range('a', 'z'):
		if c1 == c2:
			continue
		new_string = [c for c in s if c == c1 or c == c2]
		new_string_len = len(new_string)
		if is_alternating(new_string) and new_string_len > 1:
			if new_string_len > max_len:
				max_len = new_string_len
print(max_len)


n = int(input())
s = list(input())
ans = 0
for i in set(s):
	for j in set(s):
		if j != i:
			temp = [k for k in s if k == j or k == i]
			f = 0
			for z in range(1, len(temp)):
				if temp[z] == temp[z - 1]:
					f = 1
					break
			if f == 0:
				if len(temp) > ans:
					ans = len(temp)
print(ans)


n = eval(input())
st = input()
s = set(st)
max = 0
for a in s:
	for b in [x for x in s if x != a]:
		t = ''.join(filter(lambda x: x in [a, b], st))
		l = len(t)
		if l > max and t == t[:2] * (l // 2) + t[0] * (l % 2):
			max = l
print(max)


import string
n = int(input())
s = input()
ans = 0
for x in string.ascii_lowercase:
	for y in string.ascii_lowercase:
		if x not in s or y not in s:
			continue
		filtered = [c for c in s if c == x or c == y]
		filt_len = len(filtered)
		for i in range(1, filt_len):
			if filtered[i] == filtered[i - 1]:
				filtered = []
				break
		filt_len = len(filtered)
		if filt_len >= 2:
			ans = max(ans, filt_len)
print(ans)


n = int(input())
s = [v for v in input()]
s_set = set(s)
checked = set()
len_max = 0
for l in s_set:
	checked.add(l)
	for i in s_set.difference(checked):
		ok = True
		result = list(filter(lambda x: x == l or x == i, s))
		for i in range(len(result) - 1):
			if result[i] == result[i + 1]:
				ok = False
				break
		if ok == True and len(result) > len_max:
			len_max = len(result)
print(len_max)


n = int(input())
s = input()
c = set(s)
lmin = 0
for el in c:
	for el2 in c:
		if el != el2:
			l = 0
			prev = 'A'
			good = True
			for i in range(0, len(s)):
				if s[i] == el or s[i] == el2:
					if prev != s[i]:
						l = l + 1
						prev = s[i]
					else:
						good = False
						break
			if good:
				if lmin < l:
					lmin = l
print(lmin)


n = int(input())
s = input()

def alternate(st):
	if st == '' or st == None:
		return False
	l = len(st)
	if l == 1:
		return True
	if l == 2 and st[0] != st[1]:
		return True
	c = st[0]
	for x in st[0::2]:
		if x != c:
			return False
	c = st[1]
	for x in st[1::2]:
		if x != c:
			return False
	return True
chars = list(set([x for x in s]))
length = 0
for i in range(len(chars) - 1):
	for j in range(i + 1, len(chars)):
		c1 = chars[i]
		c2 = chars[j]
		t = (c1, c2)
		st = [x for x in s if x in t]
		if alternate(st):
			length = max(len(st), length)
print(length)


def alternating(L, M, ordered=False):
	if abs(len(L) - len(M)) > 1:
		return False
	if len(L) == 0 or len(M) == 0:
		return True
	if not ordered:
		if L[0] < M[0]:
			return alternating(L[1:], M, True)
		else:
			return alternating(M[1:], L, True)
	if M[0] < L[0]:
		return alternating(M[1:], L, True)
	else:
		return False

def createString(c, d, s):
	return ''.join(list((x for x in s if x == c or x == d)))
n = int(input())
s = input()
chars = list(set(s))
D = {}
for c in chars:
	D[c] = [i for i in range(0, len(s)) if s[i] == c]
maxi = 0
for i in range(0, len(chars)):
	for j in range(i + 1, len(chars)):
		if alternating(D[chars[i]], D[chars[j]]):
			L = len(D[chars[i]]) + len(D[chars[j]])
			if L > maxi:
				maxi = L
print(maxi)


def check(s1):
	for i in range(len(s1) - 1):
		if s1[i] == s1[i + 1]:
			return False
	return True
a = [0 for j in range(26)]
n = int(input())
s = input()
l1 = list(set(s))
max_len = 0
for i in range(len(l1)):
	for j in range(i + 1, len(l1)):
		x = l1[i]
		y = l1[j]
		s1 = ''
		for j in s:
			if j == x or j == y:
				s1 += j
		if check(s1) == True:
			max_len = max(len(s1), max_len)
print(max_len)


def select_substr_of_two_char(a, b, arr):
	res = []
	for l in arr:
		if l == a or l == b:
			res.append(l)
	return ''.join(res)

def check_t(st):
	for i in range(len(st) - 1):
		if st[i] == st[i + 1]:
			return False
	return True
n = int(input())
st = input().strip()
ar = list(set([i for i in st]))
longest_t = 0
for i in range(len(ar) - 1):
	for j in range(i + 1, len(ar)):
		sub_s = select_substr_of_two_char(ar[i], ar[j], st)
		if check_t(sub_s):
			if len(sub_s) > longest_t:
				longest_t = len(sub_s)
print(longest_t)


num = int(input())
s = input()
ans = -1
for i in range(ord('a'), ord('z')):
	for j in range(i + 1, ord('z') + 1):
		temp = ''
		for k in s:
			if ord(k) == i or ord(k) == j:
				temp += k
		size = len(temp)
		temp1 = 0
		flag = True
		for x in range(1, size):
			if temp[x] == temp[x - 1]:
				flag = False
				break
		if flag:
			ans = max(ans, size)
print(ans) if ans > 1 else print(0)


len_s = int(input())
s = input()

def get_t_len(fullstring, two_letters):
	last_letter = None
	current_size = 0
	actual_answer = ''
	for letter in fullstring:
		if letter not in two_letters:
			continue
		if letter == last_letter:
			return 0
		last_letter = letter
		current_size += 1
		actual_answer += letter
	return current_size
all_letters_in_s = set([str(ch) for ch in s])
all_letters_in_s = list(all_letters_in_s)
max_seen = 0
for (index1, letter1) in enumerate(all_letters_in_s):
	for letter2 in all_letters_in_s[index1 + 1:]:
		t_len = get_t_len(s, [letter1, letter2])
		if t_len > max_seen:
			max_seen = t_len
print(max_seen)


input()
num = input()
answer = 0
have = True
seen = set()
for a in num:
	for b in num:
		if a != b and (a, b) not in seen and ((b, a) not in seen):
			seen.add((a, b))
			seen.add((b, a))
			temp = [c for c in num if c == a or c == b]
			have = True
			for i in range(len(temp) - 1):
				if temp[i] == temp[i + 1]:
					have = False
					break
			if have:
				answer = len(temp) if len(temp) > answer else answer
print(answer)


from itertools import combinations

def alternating(s):

	def all_same(t):
		return t.count(t[0]) == len(t)
	c1 = s[0::2]
	c2 = s[1::2]
	return all_same(c1) and all_same(c2)
input()
s = input().strip()
maxlen = 0
for combination in combinations(set(s), 2):
	(a, b) = combination
	if abs(s.count(a) - s.count(b)) > 1:
		continue
	new_s = list(filter(lambda x: x in combination, s))
	if alternating(new_s):
		maxlen = max(maxlen, len(new_s))
print(maxlen)


import sys
l = int(input().strip())
s = input().strip()
ss = set(s)
maxL = 0
for i in ss:
	for j in ss:
		a = ''.join([k for k in s if k in (i, j)])
		if i != j and len(a) > maxL and (i + i not in a) and (j + j not in a):
			maxL = len(a)
print(maxL)


alp = 'abcdefghijklmnopqrstuvwxyz'
n = int(input())
s = input()
t = ''
max_t_length = 0
for i in range(len(alp)):
	for j in range(len(alp)):
		if i != j and alp[i] in s and (alp[j] in s):
			t = ''
			for i_letter in range(0, len(s)):
				if (s[i_letter] == alp[i] or s[i_letter] == alp[j]) and (len(t) == 0 or t[-1] != s[i_letter]):
					t += s[i_letter]
				elif len(t) > 0 and t[-1] == s[i_letter]:
					t = ''
					break
			max_t_length = max(max_t_length, len(t))
print(max_t_length)


from itertools import combinations
num = int(input())
s = str(input())
lst = list()
buffer = list()
for item in s:
	lst.append(item)
for item in lst:
	if buffer.count(item) == 0:
		buffer.append(item)
comb = list(combinations(buffer, 2))
prev = []
for item in comb:
	temp = list(lst)
	temp[:] = (value for value in temp if value == item[0] or value == item[1])
	status = True
	for i in range(0, len(temp) - 2):
		if temp[i] != temp[i + 2]:
			status = False
	if len(temp) > len(prev) and status == True:
		prev = temp
print(len(prev))


import sys

def valid(s):
	if len(s) <= 1:
		return False
	if s[0] == s[1]:
		return False
	if len(set(s)) > 2:
		return False
	for i in range(2, len(s)):
		if i % 2 == 0:
			if s[i] != s[0]:
				return False
		elif s[i] != s[1]:
			return False
	return True
n = int(input().strip())
s = input().strip()
r = 0
alp = 'abcdefghijklmnopqrstuvwxyz'
for k in alp:
	for l in alp:
		if k >= l:
			continue
		f = list(filter(lambda x: x == k or x == l, s))
		if valid(f):
			r = max(r, len(f))
print(r)


from itertools import combinations as Comb
n = int(input())
s = input()

def make_rep_dict(s):
	rep = {}
	for i in range(len(s) - 1):
		cur_ch = s[i]
		next_ch = s[i + 1]
		if cur_ch == next_ch:
			rep[cur_ch] = 1
	return rep

def is_violate(s):
	for i in range(len(s) - 1):
		cur_ch = s[i]
		next_ch = s[i + 1]
		if cur_ch == next_ch:
			return True
	return False

def make_new_string(s, c1, c2):
	new_s = ''
	for c in s:
		if c == c1 or c == c2:
			new_s += c
	return new_s
is_rep = True
while is_rep:
	rep_d = make_rep_dict(s)
	non_rep_string = ''
	for i in range(len(s)):
		cur_ch = s[i]
		if cur_ch in rep_d:
			pass
		else:
			non_rep_string += cur_ch
	if len(s) == len(non_rep_string):
		is_rep = False
	else:
		s = non_rep_string
unique_characters = []
rep = {}
for c in s:
	if c in rep:
		pass
	else:
		unique_characters.append(c)
max_len = 0
if len(unique_characters) > 1:
	two_sets = list(Comb(unique_characters, 2))
	for each in two_sets:
		new_s = make_new_string(s, each[0], each[1])
		if is_violate(new_s):
			pass
		elif len(new_s) > max_len:
			max_len = len(new_s)
print(max_len)


from collections import defaultdict
from operator import lt
(n, s) = (int(input()), input().strip())
counter = defaultdict(list)
for i in range(n):
	counter[s[i]].append(i)
if len(counter) < 2:
	print(0)
else:
	res = 0
	c = sorted(counter)
	m = len(c)
	for i in range(m):
		for j in range(i + 1, m):
			(u, v) = (counter[c[i]], counter[c[j]])
			(a, b) = (len(u), len(v))
			if (a == b or a == b + 1) and all(map(lt, u, v)) and all(map(lt, v, u[1:])) or ((a == b or a == b - 1) and all(map(lt, v, u)) and all(map(lt, u, v[1:]))):
				res = max(res, a + b)
	print(res)


from collections import Counter
from itertools import combinations

def r():
	return list(map(int, input().split()))

def check(a, b, s):
	next = a
	not_next = b
	for c in s:
		if c == not_next:
			return False
		if c == next:
			(next, not_next) = (not_next, next)
	return True

def solve(s):
	freqs = Counter(s)
	ans = 0
	for pair in combinations(range(26), 2):
		(a, b) = [chr(ord('a') + x) for x in pair]
		if a in freqs and b in freqs and (abs(freqs[a] - freqs[b]) <= 1):
			if check(a, b, s) or check(b, a, s):
				ans = max(ans, freqs[a] + freqs[b])
	return ans

def main():
	n = int(input())
	s = input()
	print(solve(s))
main()


length = input()
s = input().strip()
unique_chars = set()
for ch in s:
	unique_chars.add(ch)
unique_chars = sorted(list(unique_chars))
strings = {}
for i in range(len(unique_chars)):
	for j in range(i + 1, len(unique_chars)):
		two_chars = (unique_chars[i], unique_chars[j])
		strings[two_chars] = ''
for ch in s:
	for two_chars in strings.keys():
		if ch in two_chars:
			if strings[two_chars] is not None and len(strings[two_chars]) > 0 and (strings[two_chars][-1] == ch):
				strings[two_chars] = None
			if strings[two_chars] is not None:
				strings[two_chars] += ch
answer = 0
for two_chars in strings.keys():
	if strings[two_chars] is not None and len(strings[two_chars]) > 1:
		answer = max(answer, len(strings[two_chars]))
print(answer)


import string
from itertools import combinations
N = int(input())
S = input()
ans = 0
for (x, y) in combinations(string.ascii_lowercase, 2):
	extracted = []
	for s in S:
		if s in [x, y]:
			extracted.append(s)
	if len(extracted) < 2 or all((extracted[0] == x for x in extracted)):
		continue
	(odd, even) = (extracted[::2], extracted[1::2])
	assert len(odd) and len(even)
	if all((odd[0] == x for x in odd)) and all((even[0] == x for x in even)):
		ans = max(ans, len(extracted))
print(ans)


def get_max_len(s, q):
	if s[0] > q[0]:
		(first, second) = (q, s)
	else:
		(first, second) = (s, q)
	if not 0 <= len(first) - len(second) <= 1:
		return 0
	prev = -1
	for (a, b) in zip(first, second):
		if not prev < a < b:
			return 0
		prev = b
	if len(first) > len(second) and first[-1] < second[-1]:
		return 0
	return len(first) + len(second)

def is_valid(s):
	prev = s[0]
	for i in s:
		if prev + 1 == i:
			return False
		prev = i
	return True
n = int(input())
s = input()
index = {}
for (i, c) in enumerate(s):
	index.setdefault(c, []).append(i)
index = [(k, v) for (k, v) in index.items() if is_valid(v)]
m = len(index)
max_len = 0
for i in range(m - 1):
	for j in range(i + 1, m):
		max_len = max(max_len, get_max_len(index[i][1], index[j][1]))
print(max_len)


import itertools as it
l = int(input().strip())
s = input().strip()
ls = list(s)
chars = frozenset(ls)
itr = it.combinations(chars, 2)
max_length = 0
for selected in itr:
	t = ''.join(filter(lambda c: c in selected, ls))
	if len(frozenset(t[::2])) == 1 and len(frozenset(t[1::2])) == 1:
		max_length = max(max_length, len(t))
print(max_length)


import sys
n = int(input().strip())
s = input().strip()
alph = set()
for x in s:
	alph.add(x)
alph = sorted(alph)
ml = 0
for i in range(len(alph) - 1):
	for k in range(i + 1, len(alph)):
		found = True
		nxt = ''.join(filter(lambda x: x == alph[i] or x == alph[k], s))
		last = None
		for c in nxt:
			if not last or last != c:
				last = c
			else:
				found = False
				break
		if found:
			ml = max(ml, len(nxt))
print(ml)


def rem(s, a, b):
	t = ''
	for c in s:
		if c == a or c == b:
			t += c
	lent = len(t)
	for i in range(0, lent - 1):
		(c1, c2) = (t[i], t[i + 1])
		if c1 == c2:
			return 0
	return lent
A = 'abcdefghijklmnopqrstuvwxyz'
n = int(input().strip())
s = input().strip()
lens = len(s)
if lens == 1:
	print(0)
else:
	P = []
	for i in range(0, 25):
		c1 = A[i]
		if c1 not in s:
			continue
		for j in range(i + 1, 26):
			c2 = A[j]
			if c2 in s:
				P.append((c1, c2))
	ans = 0
	for p in P:
		(c1, c2) = (p[0], p[1])
		len1 = rem(s, c1, c2)
		if ans < len1:
			ans = len1
		len2 = rem(s, c2, c1)
		if ans < len2:
			ans = len2
	print(ans)


def fun(st, n, c1, c2):
	if st.index(c1) < st.index(c2):
		prev = c1
		flag = True
		ans = 1
		for i in range(st.index(c1) + 1, n):
			if st[i] == prev:
				flag = False
				break
			if (st[i] == c1 or st[i] == c2) and st[i] != prev:
				prev = st[i]
				ans += 1
		if flag == False:
			return 0
		return ans
	else:
		prev = c2
		flag = True
		ans = 1
		for i in range(st.index(c2) + 1, n):
			if st[i] == prev:
				flag = False
				break
			if (st[i] == c1 or st[i] == c2) and st[i] != prev:
				prev = st[i]
				ans += 1
		if flag == False:
			return 0
		return ans
n = int(input())
s = input()
d = {}
for i in range(97, 123):
	d[chr(i)] = 0
for i in s:
	d[i] += 1
res = 0
for i in range(97, 122):
	if d[chr(i)] != 0:
		for j in range(i + 1, 123):
			if d[chr(j)] != 0:
				res = max([res, fun(s, n, chr(i), chr(j))])
print(res)


import sys
max_length = 0

def check(li):
	for i in range(len(li) - 1):
		if li[i] == li[i + 1]:
			return False
	return True
length = int(input().strip())
if length == 1:
	print(0)
	exit()
s = input().strip()
chars = []
for each in s:
	if each not in chars:
		chars.append(each)
if len(chars) == 1:
	print(0)
	exit()
for i in range(len(chars) - 1):
	for j in range(i + 1, len(chars)):
		li = []
		for each in s:
			if each in [chars[i], chars[j]]:
				li.append(each)
		is_t = check(li)
		if is_t and len(li) > max_length:
			max_length = len(li)
print(max_length)


import sys
length = int(input().strip())
s = input().strip()
l = list(s)
letters = set(l)
longest = 0

def good(l):
	if len(l) < 2:
		return True
	for i in range(len(l) - 1):
		if l[i] == l[i + 1]:
			return False
	return True
for l1 in letters:
	for l2 in letters:
		if l1 != l2:
			newList = [i for i in l if i == l1 or i == l2]
			if len(newList) > longest and good(newList):
				longest = len(newList)
print(longest)


def isValid(st):
	flag = True
	for i in range(1, len(st)):
		if st[i] == st[i - 1]:
			flag = False
			break
	if flag:
		return len(st)
	return 0
n = int(input())
st = input()
all_char = list(set(st))
ans = 0
for i in range(len(all_char)):
	for j in range(i + 1, len(all_char)):
		stt = ''
		for k in st:
			if k == all_char[i] or k == all_char[j]:
				stt += k
		ans = max(ans, isValid(stt))
print(ans)


from collections import defaultdict

def check_alternate(s):
	if len(set(s)) == 2:
		a = [c for (i, c) in enumerate(s) if i % 2 == 0]
		b = [c for (i, c) in enumerate(s) if i % 2 == 1]
		return len(set(a)) == 1 and len(set(b)) == 1
	else:
		return False

def remove_all_but(s, x, y):
	final = []
	for i in range(len(s)):
		if s[i] in [x, y]:
			final.append(i)
	s = [s[i] for i in final]
	return ''.join(s)
lens = input()
s = input().strip()
letters = defaultdict(int)
for letter in s:
	letters[letter] += 1
sorted_letters = sorted(letters, key=letters.get, reverse=True)
occ = [letters[letter] for letter in sorted_letters]
ans = 0
for i in range(len(occ)):
	for j in range(i):
		if occ[j] + occ[i] < ans:
			continue
		if check_alternate(remove_all_but(s, sorted_letters[j], sorted_letters[i])):
			ans = occ[j] + occ[i]
print(ans)


from copy import deepcopy
l = int(input())
s = input()
if l == 1:
	print(0)
else:
	dic = {}
	for i in range(len(s)):
		c = s[i]
		if c not in dic:
			dic[c] = []
		dic[c].append(i)
	keys = sorted(dic.keys())
	res = 0
	for i in range(len(keys) - 1):
		for j in range(i + 1, len(keys)):
			lii = deepcopy(dic[keys[i]])
			lij = deepcopy(dic[keys[j]])
			lii.extend(lij)
			lii.sort()
			cnt = 0
			for k in range(1, len(lii)):
				if s[lii[k - 1]] == s[lii[k]]:
					break
				else:
					cnt = cnt + 1
			if cnt == len(lii) - 1 and res < len(lii):
				res = len(lii)
	print(res)


from itertools import combinations
import sys

def getUniqueCharacters(s):
	return set(s)

def getNumUniqueCharacters(s):
	return len(getUniqueCharacters(s))

def containsTwoUniqueCharacters(s):
	return getNumUniqueCharacters(s) == 2

def isValid(s):
	if containsTwoUniqueCharacters(s):
		prevChar = s[0]
		otherChar = s[1]
		if prevChar == otherChar:
			return 0
		tempChar = otherChar
		for c in s[2:]:
			if tempChar == c:
				return 0
			tempChar = c
		return len(s)
	return 0
length = int(input().strip())
s = input().strip()
uniqueChars = getUniqueCharacters(s)
if len(uniqueChars) < 2:
	print(0)
	sys.exit(0)
tuples = list(combinations(uniqueChars, len(uniqueChars) - 2))
max = 0
for tuple in tuples:
	temp = s
	for (i, a) in enumerate(tuple):
		temp = temp.replace(a, '')
	current = isValid(temp)
	if current > max:
		max = current
print(max)


import sys
l = int(input().strip())
s = list(input().strip())
c = list(set(s))
lc = len(c)
x = 0
for i in range(lc):
	for j in range(i + 1, lc):
		nl = [k for k in s if k in [c[i], c[j]]]
		ll = len(nl)
		for k in range(ll - 1):
			if nl[k] == nl[k + 1]:
				break
		else:
			x = max(x, ll)
print(x)


_ = int(input().strip())
s = input().strip()
letters = list(set([c for c in s]))
res = 0
for (i, a) in enumerate(letters):
	if a + a in s:
		continue
	for b in letters[i + 1:]:
		t = ''.join((c for c in s if c == a or c == b))
		if a + a in t:
			continue
		if b + b in t:
			continue
		if res < len(t):
			res = len(t)
print(res)


n = int(input())
s = input()
c = {}
d = []
for ch in s:
	if ch in c:
		c[ch] += 1
	else:
		c[ch] = 1
		d.append(ch)
sum = 0
for ch in c:
	sum += c[ch]
if len(d) < 0:
	print(0)
else:
	res = 0
	for i in range(len(d)):
		ci = c[d[i]]
		si = d[i] + d[i]
		for j in range(i + 1, len(d)):
			cj = c[d[j]]
			sj = d[j] + d[j]
			l = []
			ok = True
			for ch in s:
				if ch == d[i] or ch == d[j]:
					l.append(ch)
					if len(l) > 1 and l[len(l) - 1] == l[len(l) - 2]:
						ok = False
						break
			if ok:
				res = max(res, ci + cj)
	print(res)


import sys
len_s = int(input().strip())
s = input().strip()
set_s = list(set(s))

def checkT(string):
	for i in range(len(string) - 1):
		if string[i] == string[i + 1]:
			return False
	return True

def considerCharacters(string, char_set):
	char_array = list(string)
	new_char_array = []
	for i in range(len(char_array)):
		if char_array[i] in char_set:
			new_char_array.append(char_array[i])
	return ''.join(new_char_array)
maxLength = 0
for i in range(len(set_s)):
	for j in range(i + 1, len(set_s)):
		char_list = [set_s[i], set_s[j]]
		t_string = considerCharacters(s, char_list)
		if checkT(t_string) and len(t_string) > maxLength:
			maxLength = len(t_string)
print(maxLength)


import sys
s_len = int(input())
s = list(input())
set_s = list(set(s))
pairs = []
for i in range(len(set_s) - 1):
	for j in range(i + 1, len(set_s)):
		pairs.append([set_s[i], set_s[j]])
max_len = 0
for i in range(len(pairs)):
	temp_s = s[:]
	j = 0
	while j <= len(temp_s) - 1:
		if temp_s[j] == pairs[i][0] or temp_s[j] == pairs[i][1]:
			j += 1
		else:
			temp_s.pop(j)
	count = 1
	for j in range(len(temp_s) - 1):
		if temp_s[j] == temp_s[j + 1]:
			break
		else:
			count += 1
	if count == len(temp_s) and len(temp_s) > max_len:
		max_len = len(temp_s)
print(max_len)


def isValid(a):
	i = 0
	while i < len(a) - 2:
		if a[i + 2] != a[i]:
			return False
		i += 1
	return True

def sepS(c1, x1, y1):
	c2 = [x1, y1]
	return [iii for iii in c1 if iii in c2]
ln = int(input().strip())
s = input().strip()
f = list(set(s.strip('')))
m = 0
for x in f:
	for y in f:
		if x != y:
			s1 = [str(ii) for ii in s.strip('')]
			kk = sepS(s1, x, y)
			if isValid(kk):
				m = max(len(kk), m)
print(m)


import sys
len = int(input().strip())
s = input().strip()
chars = list(set(s))
maxcount = 0
for i in range(int(chars.__len__()) - 1):
	for j in range(i + 1, int(chars.__len__())):
		c1 = chars[i]
		c2 = chars[j]
		current = None
		count = 0
		for c in s:
			if c == c1:
				if current is None or current == c2:
					current = c1
					count += 1
				else:
					count = 0
					break
			elif c == c2:
				if current is None or current == c1:
					current = c2
					count += 1
				else:
					count = 0
					break
		if count > maxcount:
			maxcount = count
print(maxcount)


import itertools

def isAlternate(s):
	x = s[0]
	y = s[1]
	if x == s:
		return 0
	else:
		for i in range(2, len(s)):
			if i % 2 == 0:
				if s[i] != x:
					return 0
			elif s[i] != y:
				return 0
	return 1

def difchars(s):
	res = []
	for char in s:
		if char not in res:
			res.append(char)
	return res

def letthese(s, a, b):
	res = ''
	for elem in s:
		if elem in [a, b]:
			res = res + elem
	return res
N = input()
s = input()
res = 0
for couple in list(itertools.combinations(difchars(s), 2)):
	s2 = letthese(s, couple[0], couple[1])
	if len(s2) > max(1, res) and isAlternate(s2):
		res = len(s2)
print(res)


import sys
from collections import Counter

def strip_duplicates(arr):
	prev_char = None
	_changed = 0
	deleted_chars = 0
	for char in arr:
		if char == prev_char:
			arr = delete_char(arr, char)
			deleted_chars += 1
			_changed = 1
			break
		prev_char = char
	return (arr, deleted_chars, _changed)

def has_duplcates(arr):
	prev_char = None
	for char in arr:
		if char == prev_char:
			return True
		prev_char = char
	return False

def delete_char(arr, char):
	return [s for s in arr if char not in s]

def get_min(ccc):
	for key in ccc.keys():
		if ccc[key] == min(ccc.values()):
			return key
	return False

def try_rem_min(arr, minval):
	arr = delete_char(arr, minval)
	changed = 1
	deleted_chars = 1
	while changed == 1:
		(arr, recently_deleted_chars, changed) = strip_duplicates(arr)
		deleted_chars += recently_deleted_chars
	return (arr, deleted_chars)

def gen_charcount(arr):
	c = Counter(arr)
	cc = dict()
	for char in 'abcdefghijklmnopqrstuvwxyz':
		if c[char] > 0:
			cc[char] = c[char]
	return cc

def filter_arr(s, c, d):
	newarr = []
	for i in s:
		if i in c or i in d:
			newarr.append(i)
	return newarr
lenx = int(input().strip())
s = input().strip()
s = [x for x in s]
ms = set(s)
char_del = 0
max_valid = 0
for c in ms:
	for d in ms:
		if c != d:
			arr = filter_arr(s, c, d)
			if not has_duplcates(arr) and len(arr) > max_valid:
				max_valid = len(arr)
				stri = arr
print(max_valid)


import itertools
import re

def main():
	n = int(input().strip())
	s = input().strip()
	chars = list(set(s))
	validstrings = []
	l = len(chars)
	combinations = set(itertools.combinations(chars, 2))
	for (i, j) in combinations:
		delchars = chars.copy()
		delchars.remove(i)
		delchars.remove(j)
		t = s
		for char in delchars:
			t = t.replace(char, '')
		if len(t) >= 2:
			a = t[0]
			b = t[1]
			if checkpattern(a, b, t):
				validstrings.append(t)
	lengths = [len(str) for str in validstrings]
	if lengths != []:
		print(max(lengths))
	else:
		print(0)

def checkpattern(a, b, t):
	pattern = '^(' + re.escape(a) + re.escape(b) + ')+' + a + '?$'
	if re.match(pattern, t):
		return True
main()


import itertools
number = int(input())
string = input()
result = 0
letters = set(string)
if number > 2 and len(letters) > 2:
	temp_variants = itertools.combinations(letters, len(letters) - 2)
	for variant in temp_variants:
		temp_string = string
		for var in variant:
			temp_string = temp_string.replace(var, '')
		temp_string_len = len(temp_string)
		if temp_string == temp_string[:2] * (temp_string_len // 2) or temp_string == (temp_string[:2] * (temp_string_len // 2 + 1))[:-1]:
			if result < temp_string_len:
				result = temp_string_len
elif number == 2 and len(letters) == 2:
	result = 2
elif number < 2 or len(letters) < 2:
	pass
elif string == string[:2] * (len(string) // 2) or string == (string[:2] * (len(string) // 2 + 1))[:-1]:
	if result < len(string):
		result = len(string)
print(result)


n = int(input())
s = input()

def check_valid(s):
	if len(s) >= 2:
		first = s[0]
		second = s[1]
		if first != second:
			for (count, i) in enumerate(list(s)):
				if count % 2 == 0:
					if i != first:
						return False
				elif i != second:
					return False
			return True
	return False

def replace_chain(s, lista):
	for l in lista:
		s = s.replace(l, '')
	return s
to_delete = set(s)
biggest = 0
for first in to_delete:
	for second in to_delete:
		if first != second:
			new_to_delete = set(to_delete)
			new_to_delete.remove(first)
			new_to_delete.remove(second)
			new_s = replace_chain(s, new_to_delete)
			if check_valid(new_s):
				if len(new_s) > biggest:
					biggest = len(new_s)
print(biggest)


import sys
len = int(input().strip())
s = input().strip()

def solution(s):
	if not s:
		return 0
	alphabet = set(s)
	result = 0
	for a in alphabet:
		for b in alphabet:
			if a != b:
				result = max(result, cotigo(s, a, b))
	return result

def cotigo(s, a, b):
	count = 0
	(pa, pb) = (-1, -1)
	for (i, char) in enumerate(s):
		if char == a:
			if pa > pb:
				return 0
			(pa, count) = (i, count + 1)
		if char == b:
			if pb > pa:
				return 0
			(pb, count) = (i, count + 1)
	return count
print(solution(s))


import sys
length = int(input().strip())
s = input().strip()
if length == 2 and s[0] != s[1]:
	print(2)
	sys.exit()
if length == 2:
	print(0)
	sys.exit()
if length == 3:
	if s[0] == s[2] and s[0] != s[1]:
		print(3)
	elif s[0] == s[1] and s[1] == s[2]:
		print(0)
	elif s[0] == s[2] and s[0] != s[1]:
		print(2)
	sys.exit()
if length == 1:
	print(0)
	sys.exit()

def getCharsInString(string):
	letter_list = {}
	for letter in string:
		if letter not in letter_list:
			letter_list[letter] = 0
		letter_list[letter] += 1
	return letter_list
letter_dict = getCharsInString(s)
letter_list = reversed(sorted(letter_dict, key=lambda i: int(letter_dict[i])))
letter_list = list(letter_list)
for index in range(len(letter_list) - 1):
	for index2 in range(index + 1, len(letter_list) - 1):
		letter1 = letter_list[index]
		letter2 = letter_list[index2]
		if letter_dict[letter1] == letter_dict[letter2] or letter_dict[letter1] - 1 == letter_dict[letter2]:
			s_copy = list(s)
			a = 0
			while a < len(s_copy):
				if s_copy[a] != letter1 and s_copy[a] != letter2:
					s_copy.pop(a)
				else:
					a += 1
			flag = False
			one = s_copy[0]
			for i in range(0, len(s_copy), 2):
				if s_copy[i] != one:
					flag = True
			two = s_copy[1]
			for i in range(1, len(s_copy), 2):
				if s_copy[i] != two:
					flag = True
			if flag == False:
				print(len(s_copy))
				sys.exit()
print(0)


import sys

def longestalt(s):
	clist = list(set(s))
	best = 0
	for (i1, c1) in enumerate(clist):
		for c2 in clist[:i1]:
			sdel = [c for c in s if c in (c1, c2)]
			if all((c == sdel[i & 1] for (i, c) in enumerate(sdel))):
				best = max(best, len(sdel))
	return best
length = int(input().strip())
s = input().strip()
print(longestalt(s))


def solve():
	l = int(input())
	s = list(input())
	flag = 1
	while flag:
		flag = 0
		for i in range(len(s) - 1):
			if s[i] == s[i + 1]:
				flag = 1
				s = list(filter(s[i].__ne__, s))
				break
	count = 0
	s1 = list(set(s))
	if len(s1) < 2:
		return 0
	elif len(s1) == 2:
		return len(s)
	for i in range(len(s1) - 1):
		for j in range(i, len(s1)):
			t = ''
			for x in s:
				if x == s1[i] or x == s1[j]:
					t += x
			if t.count(s1[i] + s1[i]) == 0 and t.count(s1[j] + s1[j]) == 0:
				count = max(count, len(t))
	return count
print(solve())


import sys

def longestalt(s):
	chs = set(s)
	count = 0
	for i in chs:
		for j in chs:
			if i != j:
				cur = filterstr(s, i + j)
				if checkcondition(cur):
					count = max(count, len(cur))
	return count

def filterstr(s, keep):
	return ''.join((c for c in s if c in keep))

def checkcondition(s):
	if len(s) == 1:
		return True
	(ch1, ch2) = (s[0], s[1])
	for i in range(len(s)):
		if i % 2 == 0 and s[i] != ch1:
			return False
		elif i % 2 != 0 and s[i] != ch2:
			return False
	return True
length = int(input().strip())
s = input().strip()
print(longestalt(s))


import sys
from string import ascii_lowercase
len = int(input().strip())
s = input().strip()
result = 0
if len > 1:
	for x in ascii_lowercase:
		for y in ascii_lowercase:
			prev = None
			count = 0
			for i in range(len):
				if s[i] == x or s[i] == y:
					if s[i] != prev:
						count += 1
						prev = s[i]
					else:
						count = 0
						break
			result = max(count, result)
print(result)


import itertools
n = int(input())
s = input()
characters = list(set(s))
if len(characters) < 2:
	print(0)
else:
	validLen = 0
	for pair in itertools.product(characters, repeat=2):
		newS = ''
		for ch in s:
			if ch in pair:
				newS += ch
		valid = True
		for i in range(len(newS) - 1):
			if newS[i] == newS[i + 1]:
				valid = False
		if valid:
			if len(newS) > validLen:
				validLen = len(newS)
	print(validLen)


import sys
len = int(input().strip())
s = input().strip()
ss = set(list(s))
maxfound = 0
for x in ss:
	for y in ss:
		if x == y:
			continue
		temp = ''
		found = True
		tot = 0
		for z in s:
			if z == x or z == y:
				if temp == z:
					found = False
					break
				else:
					temp = z
					tot += 1
		if found and tot > maxfound:
			maxfound = tot
print(maxfound)


import sys
import re
from itertools import combinations
patRep = re.compile('([a-z])([a-z])(\\1\\2)+\\1?|\\A([a-z])([a-z])\\4\\Z|\\A..\\Z')
len_s = int(input().strip())
s = input().strip()
set_s = set(s)

def allTests():
	for i in combinations(set_s, 2):
		test = s
		pat = '[^' + ''.join(i) + ']'
		replaced_test = re.sub(pat, '', test)
		if len(set(replaced_test)) == 2 and (not re.search('([a-z])\\1+', replaced_test)) and patRep.match(replaced_test):
			yield len(replaced_test)
try:
	print(max(allTests()))
except:
	print(0)


import itertools

def has_adjacent_vals(s):
	for i in range(len(s) - 1):
		if s[i] == s[i + 1]:
			return True
	return False
int(input().strip())
s = input().strip()
(res, new_str) = ('', '')
chars = set(s)
if len(chars) == 2 and (not has_adjacent_vals(s)):
	res = s
elif len(chars) - 2 >= 0:
	for perm in itertools.combinations(chars, len(chars) - 2):
		new_str = s
		for c in perm:
			new_str = new_str.replace(c, '')
			if not has_adjacent_vals(new_str) and len(set(new_str)) == 2:
				if len(new_str) > len(res):
					res = new_str
print(len(res))


import sys

def verify(s_list):
	s_set = set(s_list)
	if len(s_set) != 2:
		return False
	(c1, c2) = list(s_set)
	if s_list[0] == c2:
		(c1, c2) = (c2, c1)
	chars = (c1, c2)
	for i in range(len(s_list)):
		if s_list[i] != chars[i % 2]:
			return False
	return True

def has_twin(s_list, c):
	i1 = -100
	for i in range(len(s_list)):
		if s_list[i] == c:
			if i - i1 == 1:
				return False
			i1 = i
	return False

def remove_char(s_list, char):
	return list(filter(lambda c: c != char, s_list))
n = int(input().strip())
s = input().strip()
s_curr = list(s)
s_set = set(s_curr)
chars = list(s_set)
for c in chars:
	if has_twin(s_curr, c):
		s_curr = remove_char(s_curr, c)
		s_set.remove(c)
max_len = 0
chars = list(s_set)
for i1 in range(len(chars) - 1):
	for i2 in range(i1 + 1, len(chars)):
		idx = (i1, i2)
		s_curr_tmp = list(s_curr)
		s_set_tmp = set(s_set)
		for i in range(len(chars)):
			if not i in idx:
				c = chars[i]
				s_curr_tmp = remove_char(s_curr_tmp, c)
				if has_twin(s_curr, chars[i1]) or has_twin(s_curr, chars[i2]):
					break
				s_set_tmp.remove(c)
		if len(s_set_tmp) == 2:
			if verify(s_curr_tmp) and len(s_curr_tmp) > max_len:
				max_len = len(s_curr_tmp)
print(max_len)


import sys
from string import ascii_lowercase
results = [0]
l = int(input().strip())
s = input().strip()
for a in ascii_lowercase:
	for b in ascii_lowercase:
		if a == b:
			continue
		substring = [c for c in s if c == a or c == b]
		substring2 = substring[1:]
		result = len(substring)
		for i in range(len(substring2)):
			if substring[i] == substring2[i]:
				result = 0
		if result > 1:
			results.append(result)
print(max(results))


from itertools import combinations
l = int(input().strip())
s = input().strip()

def find_repeat(s):
	repeat = set()
	for i in range(1, len(s)):
		if s[i] == s[i - 1]:
			repeat.add(s[i])
	return repeat

def remove_all(s, all):
	for c in all:
		s = s.replace(c, '')
	return s

def is_ok(s):
	for i in range(1, len(s)):
		if s[i] == s[i - 1]:
			return False
	return True

def find_max(s):
	repeat = find_repeat(s)
	while len(repeat) > 0:
		s = remove_all(s, repeat)
		repeat = find_repeat(s)
	set_s = set(s)
	if len(set_s) <= 1:
		return 0
	max_t = 0
	for (x, y) in combinations(set(s), 2):
		left = remove_all(s, set_s - {x, y})
		if is_ok(left):
			max_t = max(max_t, len(left))
	return max_t
print(find_max(s))


import sys

def isAlternating(t):
	if len(t) < 2:
		return True
	c1 = t[0]
	c2 = t[1]
	if c1 == c2:
		return False
	flip = 0
	chars = (c1, c2)
	for x in t:
		if x != chars[flip]:
			return False
		flip = 1 - flip
	return True

def isolate(s, x, y):
	t = ''
	for c in s:
		if c in (x, y):
			t += c
	return t
n = int(input().strip())
s = input().strip()
chars = list(set(s))
best = 0
for (i, x) in enumerate(chars):
	for (j, y) in enumerate(chars[i + 1:]):
		t = isolate(s, x, y)
		if isAlternating(t):
			best = max(best, len(t))
print(best)


from copy import deepcopy
t = int(input())
s = input()
ss = set(s)
ans = [0]
ls = list(ss)
for i in range(len(ls) - 1):
	v = deepcopy(ls[i])
	for j in range(i + 1, len(ls)):
		w = deepcopy(ls[j])
		new_s = [x for x in s if x == v or x == w]
		count = 1
		for k in range(1, len(new_s)):
			if new_s[k] != new_s[k - 1]:
				count += 1
			else:
				count = 0
				break
		ans.append(count)
print(max(ans))


n = int(input())
s = input()
aux = {}
for i in range(n):
	if s[i] in aux:
		aux[s[i]].append(i)
	else:
		aux[s[i]] = [i]
maxT = 0
chrt = list(aux.keys())
for i in range(len(chrt) - 1):
	for j in range(i + 1, len(chrt)):
		auxL = []
		auxL += list(zip(aux[chrt[i]], chrt[i] * len(aux[chrt[i]])))
		auxL += list(zip(aux[chrt[j]], chrt[j] * len(aux[chrt[j]])))
		auxL = sorted(auxL)
		index = 1
		while index < len(auxL):
			if auxL[index][1] == auxL[index - 1][1]:
				break
			index += 1
		if index == len(auxL):
			if len(auxL) > maxT:
				maxT = len(auxL)
print(maxT)


import sys
dummy = int(input().strip())
s = input().strip()
chars = set(s)
pairs = [(a, b) for a in chars for b in chars if a < b]

def test(t):
	for i in range(len(t) - 1):
		if t[i] == t[i + 1]:
			return False
	return True
candidates = []
for pair in pairs:
	t = ''.join([c for c in s if c in pair])
	if test(t):
		candidates.append(t)
print(max([len(t) for t in candidates]) if candidates else 0)


import sys
len1 = int(input().strip())
s = input().strip()
z = list(set(s))
dict_1 = {}
dict_2 = {}
for ch in z:
	dict_1[ch] = s.count(ch)
for i in dict_1:
	for j in dict_1:
		if i != j and abs(dict_1[i] - dict_1[j]) <= 1:
			dict_2[i, j] = min(dict_1[i], dict_1[j])
max_1 = 0
for key in dict_2.keys():
	a = set(z) - set([key[0], key[1]])
	tmp = s
	for ch in a:
		tmp = tmp.replace(ch, '')
	flag = True
	for k in range(1, len(tmp)):
		if tmp[k - 1] == tmp[k]:
			flag = False
			break
	if flag == True:
		if len(tmp) > max_1:
			max_1 = len(tmp)
print(max_1)


import sys

def compareIndices(first, second):
	i1 = 0
	i2 = 0
	while i1 < len(first) and i2 < len(second):
		if i1 > i2:
			if first[i1] > second[i2]:
				i2 += 1
			else:
				return False
		elif second[i2] > first[i1]:
			i1 += 1
		else:
			return False
	return True

def isAlternating(list1, list2):
	answer = False
	if len(list1) - 1 is len(list2):
		answer = compareIndices(list1, list2)
	elif len(list1) is len(list2) - 1:
		answer = compareIndices(list2, list1)
	elif len(list1) is len(list2):
		answer = compareIndices(list1, list2) or compareIndices(list2, list1)
	else:
		return False
	return answer

def solve(s):
	options = {}
	for i in range(len(s)):
		if options.get(s[i], None) is None:
			options[s[i]] = [i]
		else:
			if options[s[i]] is False:
				continue
			if options[s[i]][-1] is i - 1:
				options[s[i]] = False
				continue
			options[s[i]].append(i)
	keys = list(options.keys())
	ans = 0
	max = 0
	for i in range(len(keys)):
		if options[keys[i]] is False:
			continue
		for x in range(i, len(keys)):
			if options[keys[x]] is False:
				continue
			if x is i:
				continue
			if isAlternating(options[keys[i]], options[keys[x]]):
				if len(options[keys[i]]) + len(options[keys[x]]) > max:
					max = len(options[keys[i]]) + len(options[keys[x]])
					ans = (options[keys[i]], options[keys[x]])
	return max
lenz = int(input().strip())
s = input().strip()
print(solve(s))


n = int(input())
s = input()
l = list(set(s))
ls = [0]
for i in range(len(l)):
	for j in range(len(l)):
		cA = l[i]
		cB = l[j]
		if cA == cB:
			continue
		p = 0
		size = 0
		sc = True
		for k in s:
			if k == cA and p == 0 or (k == cB and p == 1):
				sc = False
				break
			elif k == cA or k == cB:
				size += 1
				p = (p + 1) % 2
		if sc:
			ls.append(size)
print(max(ls))


from collections import defaultdict
l = int(input())
s = input()
x = defaultdict(list)
for i in range(l):
	x[s[i]].append(i)
c = list(x.keys())
lm = 0
for i in range(len(c)):
	for j in range(i + 1, len(c)):
		if abs(len(x[c[i]]) - len(x[c[j]])) > 1:
			continue
		(c1, c2) = (c[i], c[j]) if x[c[i]][0] < x[c[j]][0] else (c[j], c[i])
		ind = [-1]
		if len(x[c2]) > len(x[c1]):
			continue
		valid = True
		for k in range(max(len(x[c1]), len(x[c2]))):
			if k < len(x[c1]):
				if x[c1][k] < ind[-1]:
					valid = False
					break
				ind.append(x[c1][k])
			if k < len(x[c2]):
				if x[c2][k] < ind[-1]:
					valid = False
					break
				ind.append(x[c2][k])
		if valid:
			lm = max(lm, len(ind) - 1)
print(lm)


n = int(input())
string = input()
combinaciones = []
elementos = list(set(string))
el = set(string)
for i in range(len(elementos)):
	for e in range(i + 1, len(elementos)):
		combinaciones.append(list(el - set([elementos[i], elementos[e]])))
contador = 0
for e in combinaciones:
	cadena = string
	for i in e:
		cadena = cadena.replace(i, '')
	bandera = 0
	for g in range(len(cadena) - 1):
		if cadena[g] == cadena[g + 1]:
			bandera = 1
			break
	if bandera == 0:
		if contador < len(cadena):
			contador = len(cadena)
print(contador)


n = int(input())
s = input()
c = []
elem = list(set(s))
el = set(s)
for i in range(len(elem)):
	for e in range(i + 1, len(elem)):
		c.append(list(el - set([elem[i], elem[e]])))
counter = 0
for e in c:
	cad = s
	for i in e:
		cad = cad.replace(i, '')
	b = 0
	for h in range(len(cad) - 1):
		if cad[h] == cad[h + 1]:
			b = 1
			break
	if b == 0:
		if counter < len(cad):
			counter = len(cad)
print(counter)


n = int(input())
s = input()
c = []
elem = list(set(s))
el = set(s)
for i in range(len(elem)):
	for e in range(i + 1, len(elem)):
		c.append(list(el - set([elem[i], elem[e]])))
counter = 0
for e in c:
	cad = s
	for i in e:
		cad = cad.replace(i, '')
	b = 0
	for h in range(len(cad) - 1):
		if cad[h] == cad[h + 1]:
			b = 1
			break
	if b == 0:
		if counter < len(cad):
			counter = len(cad)
print(counter)


import sys
import itertools

def valid(word):
	lw = len(word)
	for (k, c) in enumerate(word[0:-1]):
		if c == word[k + 1]:
			return False
	return True
length = int(input().strip())
s = input().strip()
S = list(set(s))
L = len(S)
count = 0
for i in range(L):
	for j in range(i + 1, L):
		w = ''.join((c for c in s if c == S[i] or c == S[j]))
		if valid(w):
			count = max(count, len(w))
print(count)


import sys
from itertools import combinations
slen = int(input().strip())
s = input().strip()

def subset_letters(s, l):
	return ''.join(filter(lambda x: x in l, s))

def is_alternating(s, min_len=2):
	num_letters = len(set(s))
	if num_letters != 2 or len(s) < min_len:
		return False
	prev = None
	for c in s:
		if c == prev:
			return False
		prev = c
	return True

def get_best_length(s, verbose=False):
	pairs = combinations(set(s), 2)
	lengths = [0]
	for p in pairs:
		ss = subset_letters(s, p)
		if is_alternating(ss):
			if verbose:
				print(ss, len(ss))
			lengths.append(len(ss))
	return max(lengths)
print(get_best_length(s))


import sys
from itertools import combinations
input()
s = input().strip()
number_of_letters = len(set(s))
letters = set(s)
keys = combinations(letters, 2)
t_dict = {}
for key in keys:
	t_dict[''.join(key)] = ''
key_to_remove = []
for ch in s:
	for key in t_dict.keys():
		if ch in key:
			if t_dict[key] and ch == t_dict[key][-1]:
				key_to_remove.append(key)
			else:
				t_dict[key] += ch
	if key_to_remove:
		[t_dict.pop(r, None) for r in key_to_remove]
if t_dict.values():
	print(max(list(map(len, t_dict.values()))))
else:
	print(0)


from itertools import combinations
n = int(input())
s = input().strip()
longest = 0
for xy in combinations(set(s), 2):
	t = list(filter(lambda x: x in xy, s))
	if len(set(t[0::2])) == 1 and len(set(t[1::2])) == 1:
		longest = max(longest, len(t))
print(longest)


import sys
l = int(sys.stdin.readline())
s = sys.stdin.readline().strip()
abc = [chr(x) for x in range(ord('a'), ord('z') + 1)]
best = 0
for i in range(len(abc)):
	for j in range(i + 1, len(abc)):
		(a, b) = (abc[i], abc[j])
		(aa, bb) = (True, True)
		d = 0
		for c in s:
			if c == a:
				if aa:
					d += 1
					(aa, bb) = (False, True)
				else:
					d = 0
					break
			elif c == b:
				if bb:
					d += 1
					(aa, bb) = (True, False)
				else:
					d = 0
					break
		if d > best and d > 1:
			best = d
print(best)


import sys
N = int(input().strip())
s = input().strip()
pos = {}
for (n, letter) in enumerate(s):
	if letter in pos:
		pos[letter].append(n)
	else:
		pos[letter] = [n]
letters = list(pos.keys())
letters.sort(key=lambda x: len(pos[x]), reverse=True)
longest = 0
for a in range(len(letters)):
	A = letters[a]
	for b in range(a + 1, len(letters)):
		B = letters[b]
		if pos[A][0] < pos[B][0]:
			if len(pos[A]) - len(pos[B]) > 1:
				continue
			prev = A
			prevPos = pos[A][0]
			aPos = 1
			bPos = 0
		else:
			if len(pos[B]) < len(pos[A]):
				continue
			prev = B
			prevPos = pos[B][0]
			aPos = 0
			bPos = 1
		size = 0
		good = True
		while aPos < len(pos[A]) or bPos < len(pos[B]):
			if prev == B:
				if pos[A][aPos] < pos[B][bPos - 1]:
					good = False
					break
				aPos += 1
				prev = A
			else:
				if pos[B][bPos] < pos[A][aPos - 1]:
					good = False
					break
				bPos += 1
				prev = B
		if good:
			longest = max(longest, len(pos[A]) + len(pos[B]))
print(longest)


from re import sub
from itertools import combinations
input()
s = input()
set_ = set(s)
res = 0
pers = combinations(set(s), 2)
if len(set_) == 2:
	l = len(s)
	if all((s[i] != s[i + 1] for i in range(l - 1))):
		res = l
else:
	for p in pers:
		sl = sub('[' + ''.join(set_ - set(p)) + ']', '', s)
		l = len(sl)
		if all((sl[i] != sl[i + 1] for i in range(l - 1))) and l > res:
			res = l
print(res)


import sys

def is_alternating(char_array, allowedarray):
	current_char = None
	length = 0
	for ch in char_array:
		if ch in allowedarray:
			if ch == current_char:
				return (length, False)
			length += 1
			current_char = ch
	return (length, True)

def find_longest_sequence(char_array):
	unique_array = list(set(char_array))
	currentlength = 0
	for i in range(len(unique_array) - 1):
		for j in range(i + 1, len(unique_array)):
			(length, isalternating) = is_alternating(char_array, [unique_array[i], unique_array[j]])
			if isalternating:
				if length > currentlength:
					currentlength = length
	return currentlength
length = int(input().strip())
s = input().strip()
print(find_longest_sequence(list(s)))


import sys
len1 = int(input().strip())
s = input().strip()
s1 = set(s)
d = [(s.count(x), x) for x in s1]
d = sorted(d, key=lambda x: x[0], reverse=True)
yep = 0
maximum = 0
for x in range(len(d) - 1):
	for w in range(x + 1, len(d)):
		if d[x][0] - d[w][0] <= 1:
			temp = list(filter(lambda z: z == d[x][1] or z == d[w][1], s))
			check = 1
			for y in range(len(temp)):
				if y % 2 == 0 and temp[y] == temp[0]:
					continue
				elif y % 2 == 1 and temp[y] == temp[1]:
					continue
				else:
					check = 0
					break
			if check and d[x][0] + d[w][0] > maximum:
				maximum = d[x][0] + d[w][0]
				yep = 1
				break
if yep == 0:
	print(0)
else:
	print(maximum)


import sys
length = int(input().strip())
s = input().strip()
letters = list(set(s))
longest = 0
for i in range(len(letters) - 1):
	for j in range(i + 1, len(letters)):
		temp = (letters[i], letters[j])
		string = ''.join([letter for letter in s if letter in temp])
		n = len(string)
		if all((string[i] != string[i + 1] for i in range(len(string) - 1))) and n > longest:
			longest = n
print(longest)


n = int(input())
if n <= 1:
	print(0)
	exit()
txt = input().strip()
a = set([x for x in txt])
l = 0
if len(txt) == 2:
	if txt[0] != txt[1]:
		l = 2
else:
	while a:
		s1 = a.pop()
		for s2 in a:
			txt_2 = list(filter(lambda x: x == s1 or x == s2, txt))
			for k in range(2, len(txt_2)):
				(t1, t2, t3) = (txt_2[k - 2], txt_2[k - 1], txt_2[k])
				if not (t1 != t2 and t3 != t2 and (t1 == t3)):
					break
			else:
				l = max(l, len(txt_2))
print(l)


def calculate(string, a, b):
	potential_string = [letter for letter in string if letter == a or letter == b]
	current_letter = potential_string[0]
	length_of_potential_string = len(potential_string)
	for k in range(1, length_of_potential_string):
		if potential_string[k] == current_letter:
			return -1
		else:
			current_letter = potential_string[k]
	return len(potential_string)
input()
string = input()
letters = sorted(set(string))
max_len = 0
letter_count = len(letters)
for i in range(letter_count):
	for j in range(i + 1, letter_count):
		(a, b) = (letters[i], letters[j])
		current_result_length = calculate(string, a, b)
		if max_len < current_result_length:
			max_len = current_result_length
print(max_len)


from collections import defaultdict as dd
length = int(input().strip())
s = input().strip()
occurrences = dd(int)
bad = set()
for (i, c) in enumerate(s):
	if i + 1 < length and s[i + 1] == c:
		bad.add(c)
	occurrences[c] += 1
for c in bad:
	occurrences.pop(c, None)
possible = []
for item1 in occurrences.items():
	for item2 in occurrences.items():
		if item1[0] < item2[0]:
			possible.append([str(item1[0]) + str(item2[0]), item1[1] + item2[1]])
possible = sorted(possible, key=lambda x: x[1], reverse=True)
for p in possible:
	char1 = p[0][0]
	char2 = p[0][1]
	found = False
	first = False
	second = False
	success = True
	for c in s:
		if not found:
			if c == char1 or c == char2:
				found = True
				if c == char1:
					first = True
				elif c == char2:
					second = True
		elif c == char1:
			if first:
				success = False
				break
			else:
				first = True
				second = False
		elif c == char2:
			if second:
				success = False
				break
			else:
				second = True
				first = False
	if success:
		print(p[1])
		exit(0)
print(0)


import sys
import re
len2 = int(input().strip())
s = input().strip()
len1 = 0
list1 = list(set(s))
len3 = len(list1)
for x in range(0, len3 - 1):
	for y in range(1, len3):
		if x == y:
			continue
		s2 = list1[x] + list1[y]
		check = '[^' + s2 + ']'
		s3 = re.sub(check, '', s)
		s4 = list1[x] + list1[x]
		if s4 in s3:
			continue
		s4 = list1[y] + list1[y]
		if s4 in s3:
			continue
		temp = len(s3)
		if temp > len1:
			len1 = temp
print(len1)


def permutation(candidate, target_n):

	def do_permu(begin, res):
		nonlocal candidate, target_n, tc_pairs
		if len(res) == target_n:
			tc_pairs.append(tuple(res))
		else:
			for idx in range(begin, len(candidate)):
				res.append(candidate[idx])
				do_permu(begin + 1, res)
				res.pop()
	tc_pairs = []
	do_permu(0, [])
	return tc_pairs

def target_s(s, tc):
	idx = 0
	while idx < len(s):
		if s[idx] not in tc:
			s.pop(idx)
		else:
			idx += 1
	for idx in range(len(s) - 1):
		if s[idx] == s[idx + 1]:
			return -1
	return len(s)
SL = int(input().strip())
S = list(input().strip())
c_types = tuple(set(S))
tc_pairs = permutation(c_types, 2)
max_tsl = 0
for tc in tc_pairs:
	max_tsl = max(max_tsl, target_s(S.copy(), tc))
print(max_tsl)


import sys

def isValid(st):
	a = set()
	b = set()
	for i in range(0, len(st), 2):
		try:
			a.add(st[i])
			b.add(st[i + 1])
		except:
			pass
	return len(a) == 1 and len(b) == 1
l = int(input().strip())
s = list(input().strip())
al = list(set(s))
ans = 0
for i in al:
	for j in al:
		if i != j:
			st = ''.join([kk for kk in s if kk == i or kk == j])
			if isValid(st):
				ans = max(ans, len(st))
print(ans)


from collections import Counter

def get_smth(s, l1, l2):
	new_s = [x for x in s if x == l1 or x == l2]
	for i in range(len(new_s) - 1):
		if new_s[i] == new_s[i + 1]:
			return 0
	return len(new_s)
l = int(input().strip())
s = list(input().strip())
c = sorted(list(Counter(s).items()), key=lambda x: (x[1], x[0]), reverse=True)
res = 0
for i in range(len(c)):
	for j in range(len(c)):
		if i != j:
			if abs(c[i][1] - c[j][1]) <= 1:
				tmp_res = get_smth(s, c[i][0], c[j][0])
				if tmp_res > res:
					res = tmp_res
print(res)


import sys
n = int(input().strip())
string = input().strip()

def check_proper_string(string):
	x = 0
	y = 1
	if len(string) < 2 or string[0] == string[1]:
		return False
	while x < len(string):
		if not string[x] == string[0]:
			return False
		x += 2
	while y < len(string):
		if not string[y] == string[1]:
			return False
		y += 2
	return True
answer = 0
for char1 in list((chr(i) for i in range(97, 123, 1))):
	for char2 in list((chr(i) for i in range(97, 123, 1))):
		if char1 == char2:
			continue
		new_string = []
		for x in range(n):
			if string[x] == char1 or string[x] == char2:
				new_string.append(string[x])
		if check_proper_string(new_string):
			if len(new_string) > answer:
				answer = len(new_string)
print(answer)


import sys
from itertools import combinations
length = int(input().strip())
s = input().strip()

def IsAlternating(t):
	if t[0] == t[1]:
		return False
	for i in range(2, len(t)):
		if t[i] != t[i % 2]:
			return False
	return True

def findUnique(s):
	characters = set()
	for c in s:
		characters.add(c)
	return [c for c in characters]

def findMaxAlternatingLength(s):
	if len(s) < 2:
		return 0
	uniqueChars = findUnique(s)
	if len(uniqueChars) < 2:
		return 0
	return len(findMaxAlternatingSubsequence(s, uniqueChars))

def filterString(s, charsToKeep):
	return ''.join([c for c in s if c in charsToKeep])

def findMaxAlternatingSubsequence(s, uniqueChars):
	if IsAlternating(s):
		return s
	pairs = combinations(uniqueChars, 2)
	longerSequence = ''
	for ss in pairs:
		subsequence = filterString(s, ss)
		if IsAlternating(subsequence) and len(subsequence) > len(longerSequence):
			longerSequence = subsequence
	return longerSequence
print(findMaxAlternatingLength(s))


import sys
leng = int(input().strip())
s = input().strip()
c = list(s)
d = set(c)

def removeall(lst, el):
	r = list(filter(el.__ne__, lst))
	return r

def fin_list(lst, a, b):
	st = set(lst)
	w = list(filter(a.__ne__, list(st)))
	w = list(filter(b.__ne__, w))
	f = lst
	for el in w:
		f = removeall(f, el)
	return f

def choose_two(lst):
	g = []
	p = len(lst)
	for i in range(p):
		for j in range(i + 1, len(lst)):
			g.append([lst[i], lst[j]])
	return g

def valid_lst(lst):
	x = len(lst)
	[a, b] = list(set(lst))
	g1 = []
	for i in range(x):
		if i % 2 == 0:
			g1.append(a)
		else:
			g1.append(b)
	g2 = []
	for i in range(x):
		if i % 2 == 0:
			g2.append(b)
		else:
			g2.append(a)
	if lst == g1 or lst == g2:
		return True
	else:
		return False
q = choose_two(list(d))
max1 = 0
for [a, b] in q:
	r = fin_list(c, a, b)
	b = valid_lst(r)
	if b == True:
		if len(r) > max1:
			max1 = len(r)
print(max1)


import sys
l = int(input())
s = input()
str1 = ''.join(set(s))
a_list = []

def altenate(checkAlter):
	count = 0
	for i in range(len(checkAlter) - 2):
		if checkAlter[i] != checkAlter[i + 2]:
			count = count + 1
			break
		else:
			count = 0
	return count

def otherthan(a, b, orgstr):
	newstr = ''
	for i in orgstr:
		if i == a or i == b:
			newstr = newstr + i
	return newstr
if len(str1) > 2:
	for i in range(len(str1) + 1):
		for j in range(i + 1, len(str1)):
			rep_char1 = str1[i]
			rep_char2 = str1[j]
			newstr = otherthan(rep_char1, rep_char2, s)
			s_new = s
			s_new1 = s_new.replace(rep_char1, '')
			s_new2 = s_new.replace(rep_char2, '')
			s_new = s_new.replace(rep_char1, '')
			s_new = s_new.replace(rep_char2, '')
			a = altenate(newstr)
			if a == 0:
				a_list.append(len(newstr))
elif len(str1) == 2:
	a = altenate(s)
	if a == 0:
		a_list.append(len(s))
if a_list:
	print(max(a_list))
else:
	print(0)


import sys
import itertools
length = int(input().strip())
s = input().strip()

def is_t(string):
	if len(string) < 2:
		return False
	two = [string[0], string[1]]
	for i in range(len(string)):
		if i == len(string) - 1:
			break
		elif string[i] == string[i + 1] or string[i] not in two:
			return False
	return True

def get_len(lst):
	highest = 0
	for x in lst:
		if is_t(x):
			if len(x) > highest:
				highest = len(x)
	return highest

def get_combo(lst):
	no_dupes = list(set(s))
	combos = []
	for i in itertools.combinations(no_dupes, len(no_dupes) - 2):
		combos.append(i)
	return combos
if len(s) <= 0:
	print(0)
else:
	try:
		combinations = get_combo(s)
		lists = []
		for i in range(len(combinations)):
			lists.append(s)
		for i in range(len(combinations)):
			if is_t(lists[i]):
				pass
			elif len(combinations) <= 1:
				pass
			else:
				for z in range(len(combinations[i])):
					lists[i] = lists[i].replace(combinations[i][z], '')
		print(get_len(lists))
	except:
		print(0)


n = int(input())
s = input()
champ = 0
for i in range(26):
	for j in range(i + 1, 26):
		a = chr(i + ord('a'))
		b = chr(j + ord('a'))
		t = 0
		last = None
		for x in s:
			if x == a:
				if last == b or last == None:
					t += 1
					last = a
				else:
					break
			if x == b:
				if last == a or last == None:
					t += 1
					last = b
				else:
					break
		else:
			if t > 1:
				champ = max(champ, t)
print(champ)


import itertools
size = int(input().strip())
s = input()
t = set(s)
combi = []
lenght = 0
combi = list(itertools.combinations(t, 2))
for i in combi:
	(x, y) = (i[0], i[1])
	ans = []
	for j in range(size):
		if s[j] == x or s[j] == y:
			ans.append(s[j])
	flag = 1
	for x in range(len(ans) - 2):
		if ans[x] != ans[x + 2]:
			flag = 0
			break
	if flag == 1:
		if len(ans) > lenght:
			lenght = len(ans)
print(lenght)


import sys

def checkCombo(string, c1, c2):
	curr = None
	for c in string:
		if c == c1 or c == c2:
			if curr == None or curr != c:
				curr = c
			elif curr == c:
				return False
	return True
l = int(input().strip())
s = input().strip()
charDict = {}
for c in s:
	if c in charDict:
		charDict[c] = charDict[c] + 1
	else:
		charDict[c] = 1
highest = 0
dictKeys = list(charDict.keys())
for i in range(len(dictKeys) - 1):
	for j in range(i + 1, len(dictKeys)):
		if checkCombo(s, dictKeys[i], dictKeys[j]):
			if charDict[dictKeys[i]] + charDict[dictKeys[j]] > highest:
				highest = charDict[dictKeys[i]] + charDict[dictKeys[j]]
print(highest)


import sys
import re
l = int(input().strip())
s = input().strip()
letters = list(set(s))

def checkAlternating(s):
	if len(s) < 2:
		return True
	for i in range(len(s) - 1):
		if s[i] == s[i + 1]:
			return False
	return True
maxLen = 0
for c1i in range(len(letters)):
	for c2i in range(c1i + 1, len(letters)):
		c1 = letters[c1i]
		c2 = letters[c2i]
		extracted = ''.join(re.findall('[' + c1 + c2 + ']+', s))
		if checkAlternating(extracted):
			maxLen = max(maxLen, len(extracted))
print(maxLen)


def checkconsecutives(s, c1, c2):
	prev = ''
	for i in range(len(s)):
		if s[i] == c1 or s[i] == c2:
			if prev == s[i]:
				return False
			else:
				prev = s[i]
	return True

def FindTwoChars(s):
	hashMap = dict()
	if len(s) == 0:
		return 0
	if len(s) == 1:
		return 0
	for char in s:
		if char in 'abcdefghijklmnopqrstuvwxyz':
			if char in hashMap:
				hashMap[char] += 1
			else:
				hashMap[char] = 1
		else:
			return 0
	if len(hashMap) <= 1:
		return 0
	items = [(v, k) for (k, v) in hashMap.items()]
	items.sort()
	items.reverse()
	maxNum = 0
	for i in range(len(items)):
		if i + 1 < len(s):
			for j in range(i + 1, len(items)):
				if checkconsecutives(s, items[i][1], items[j][1]):
					maxNum = max(maxNum, items[i][0] + items[j][0])
	return maxNum
length = int(input().strip())
s = input().strip()
print(FindTwoChars(s))