The only difference between easy and hard versions is constraints.

You are given a sequence $a$ consisting of $n$ positive integers.

Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are $a$ and $b$, $a$ can be equal $b$) and is as follows: $[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$. There $x, y$ are integers greater than or equal to $0$. For example, sequences $[]$, $[2]$, $[1, 1]$, $[1, 2, 1]$, $[1, 2, 2, 1]$ and $[1, 1, 2, 1, 1]$ are three block palindromes but $[1, 2, 3, 2, 1]$, $[1, 2, 1, 2, 1]$ and $[1, 2]$ are not.

Your task is to choose the maximum by length subsequence of $a$ that is a three blocks palindrome.

You have to answer $t$ independent test cases.

Recall that the sequence $t$ is a a subsequence of the sequence $s$ if $t$ can be derived from $s$ by removing zero or more elements without changing the order of the remaining elements. For example, if $s=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$.


-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 2000$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case contains one integer $n$ ($1 \le n \le 2000$) — the length of $a$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 26$), where $a_i$ is the $i$-th element of $a$. Note that the maximum value of $a_i$ can be up to $26$.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2000$ ($\sum n \le 2000$).


-----Output-----

For each test case, print the answer — the maximum possible length of some subsequence of $a$ that is a three blocks palindrome.


-----Example-----
Input
6
8
1 1 2 2 3 2 1 1
3
1 3 3
4
1 10 10 1
1
26
2
2 1
3
1 1 1

Output
7
2
4
1
1
3

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Sorting

Amortized analysis

Complete search

Dynamic programming

Data structures


Solutions:
import sys, math, itertools
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify, nlargest
from copy import deepcopy
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))

def inpl_1():
	return list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))
M = 27
for _ in range(inp()):
	n = inp()
	A = inpl()
	aa = [[0] * (n + 1) for _ in range(M)]
	numind = [[] for _ in range(M)]
	for (i, x) in enumerate(A):
		numind[x].append(i)
		for j in range(M):
			aa[j][i + 1] = aa[j][i] + (x == j)
	res = 0
	for i in range(M):
		res = max(res, aa[i][-1])
	for a in range(1, M):
		for cnta in range(1, aa[a][-1] // 2 + 1):
			l = numind[a][cnta - 1]
			r = numind[a][aa[a][-1] - cnta]
			cnt = [0] * M
			for i in range(l, r + 1):
				if A[i] != a:
					cnt[A[i]] += 1
			ans = cnta * 2 + max(cnt)
			res = max(res, ans)
	print(res)


from bisect import bisect_left as lower_bound, bisect_right as upper_bound
from sys import stdin, stdout

def main():
	t = int(stdin.readline())
	for _ in range(t):
		n = int(stdin.readline())
		a = list(map(int, stdin.readline().strip().split()))
		(pre, su) = ({i: [] for i in range(27)}, {i: [] for i in range(27)})
		for (i, num) in enumerate(a):
			su[num].append(i)
		ret = 1
		for (i, num) in enumerate(a):
			pre[num].append(i)
			su[num].pop(0)
			x = min(len(pre[num]), len(su[num]))
			if x == 0:
				continue
			(lo, hi) = (pre[num][x - 1], su[num][len(su[num]) - x])
			y = 0
			for j in range(27):
				p = lower_bound(su[j], hi)
				q = upper_bound(su[j], lo)
				y = max(y, p - q)
			ret = max(ret, 2 * x + y)
		print(ret)
main()


from collections import defaultdict
t = int(input())
for _ in range(t):
	n = int(input())
	ans = 0
	arr = list(map(int, input().strip().split()))
	cnt = [[0 for i in range(201)] for j in range(n)]
	freq = defaultdict(int)
	ind = defaultdict(list)
	for j in range(n):
		freq[arr[j]] += 1
		for i in range(201):
			cnt[j][i] = (cnt[j - 1][i] if j > 0 else 0) + (i == arr[j])
		ans = max(ans, freq[arr[j]])
		ind[arr[j]].append(j)
	for a in range(201):
		for sz in range(1, n + 1):
			if 2 * sz <= len(ind[a]):
				r = ind[a][sz - 1]
				l = ind[a][len(ind[a]) - sz]
				bb = 0
				for b in range(201):
					if b != a:
						bb = max(bb, cnt[l][b] - cnt[r][b])
				ans = max(ans, bb + 2 * sz)
			else:
				break
	print(ans)


import sys
import math
T = int(sys.stdin.readline())
for _ in range(T):
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	pos = [[] for _ in range(27)]
	for (i, x) in enumerate(a):
		pos[x].append(i + 1)
	pre_sum = [[0] * (n + 1) if pos[i] else [] for i in range(27)]
	for (i, x) in enumerate(a):
		pre_sum[x][i + 1] = 1
	for x in range(1, 27):
		if pre_sum[x]:
			for i in range(1, n + 1):
				pre_sum[x][i] += pre_sum[x][i - 1]
	ans = 0
	for x in range(1, 27):
		if pos[x]:
			x_num = len(pos[x])
			ans = max(ans, x_num)
			mid = x_num // 2
			for j in range(mid):
				left = j
				right = x_num - 1 - j
				left_pos = pos[x][left]
				right_pos = pos[x][right]
				for y in range(1, 27):
					if pos[y] and y != x:
						ans = max(ans, pre_sum[y][right_pos] - pre_sum[y][left_pos] + (j + 1) * 2)
	print(ans)


tc = int(input())
while tc > 0:
	n = int(input())
	a = list(map(int, input().split()))
	cnt = [[0] * 26]
	for i in range(1, n + 1):
		cnt.append(cnt[i - 1].copy())
		cnt[i][a[i - 1] - 1] += 1
	chars = set(filter(lambda c: cnt[n][c] > 0, range(26)))
	ans = 0
	for l in range(n):
		for r in range(l, n):
			max_in = 0
			max_out = 0
			for c in chars:
				max_in = max(max_in, cnt[r + 1][c] - cnt[l][c])
				max_out = max(max_out, min(cnt[l][c], cnt[n][c] - cnt[r + 1][c]) * 2)
			ans = max(ans, max_in + max_out)
	print(ans)
	tc -= 1


import math
import sys
import collections
input = sys.stdin.buffer.readline

def solveAll():
	nbCases = int(input())
	for _ in range(nbCases):
		case = readCase()
		print(solve(case))

def readCase():
	input()
	return [int(x) for x in input().split()]

def solve(nums):
	indices = [[] for _ in range(201)]
	for (i, num) in enumerate(nums):
		indices[num] += [i]
	bucket = buildBucket(nums)
	ans = -math.inf
	for num in range(1, 201):
		ans = max(ans, computeThreeBlock(nums, indices[num], bucket.copy()))
	return ans

def buildBucket(nums):
	if len(nums) <= 200:
		return collections.Counter(nums)
	else:
		bucket = [0] * 201
		for num in nums:
			bucket[num] += 1
		return bucket

def computeThreeBlock(nums, indices, bucket):
	le = 0
	ri = len(nums) - 1
	indicesFrom = 0
	indicesTo = len(indices) - 1
	ans = -math.inf
	while indicesFrom <= indicesTo:
		while le <= indices[indicesFrom]:
			bucket[nums[le]] -= 1
			le += 1
		while ri >= indices[indicesTo]:
			bucket[nums[ri]] -= 1
			ri -= 1
		if indicesFrom < indicesTo:
			ans = max(ans, getMaxValue(bucket, len(nums)) + 2 * (indicesFrom + 1))
		else:
			ans = max(ans, getMaxValue(bucket, len(nums)) - 1 + 2 * (indicesFrom + 1))
		indicesFrom += 1
		indicesTo -= 1
	return ans

def getMaxValue(bucket, n):
	if n > 200:
		return max(bucket)
	else:
		return max(0, max(bucket.values()))
solveAll()


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
t = int(input())
for tests in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	COUNT = [[0] * 27 for i in range(n)]
	for i in range(n):
		for j in range(1, 27):
			COUNT[i][j] = COUNT[i - 1][j]
		COUNT[i][A[i]] += 1
	ANS = 1
	for i in range(1, 27):
		bind = 0
		eind = n - 1
		score = 0
		while bind < eind:
			while bind < n and A[bind] != i:
				bind += 1
			while eind >= 0 and A[eind] != i:
				eind -= 1
			if bind < eind:
				score += 2
				C = [0] * 27
				for j in range(27):
					C[j] = COUNT[eind - 1][j] - COUNT[bind][j]
				ANS = max(ANS, score + max(C))
				bind += 1
				eind -= 1
	print(ANS)


t = int(input())
for g in range(t):
	n = int(input())
	L = list(map(int, input().split()))
	maxsize = 0
	for a in range(1, 27):
		for b in range(1, 27):
			Lab = list()
			aocc = 0
			bocc = 0
			for k in range(n):
				if L[k] == a:
					aocc += 1
					Lab.append(L[k])
				elif L[k] == b:
					bocc += 1
					Lab.append(L[k])
			size = aocc + bocc
			i = 0
			j = size - 1
			if i == j:
				maxsize = max(maxsize, bocc)
			x = 0
			aright = 0
			aleft = 0
			while i < j:
				if aleft < x:
					if Lab[i] == a:
						aleft += 1
						i += 1
					else:
						i += 1
						bocc -= 1
				if aright < x:
					if Lab[j] == a:
						aright += 1
						j -= 1
					else:
						j -= 1
						bocc -= 1
				if aright == x and aleft == x:
					maxsize = max(maxsize, 2 * x + bocc)
					x += 1
	print(maxsize)


import math

def solveAll():
	nbCases = int(input())
	for _ in range(nbCases):
		case = readCase()
		print(solve(case))

def readCase():
	input()
	return [int(x) for x in input().split()]

def solve(nums):
	indices = [[] for _ in range(201)]
	for (i, num) in enumerate(nums):
		indices[num] += [i]
	ans = -math.inf
	for num in range(1, 201):
		ans = max(ans, computeThreeBlock(nums, indices[num]))
	return ans

def computeThreeBlock(nums, indices):
	bucket = [0] * 201
	for num in nums:
		bucket[num] += 1
	le = 0
	ri = len(nums) - 1
	indicesFrom = 0
	indicesTo = len(indices) - 1
	ans = -math.inf
	while indicesFrom <= indicesTo:
		while le <= indices[indicesFrom]:
			bucket[nums[le]] -= 1
			le += 1
		while ri >= indices[indicesTo]:
			bucket[nums[ri]] -= 1
			ri -= 1
		if indicesFrom < indicesTo:
			ans = max(ans, max(bucket) + 2 * (indicesFrom + 1))
		else:
			ans = max(ans, max(bucket) - 1 + 2 * (indicesFrom + 1))
		indicesFrom += 1
		indicesTo -= 1
	return ans
solveAll()


t = int(input())
for q in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	sl = [[] for i in range(201)]
	ss = [[0] for i in range(201)]
	for i in range(n):
		sl[l[i]].append(i)
		for j in range(201):
			ss[j].append(ss[j][-1])
		ss[l[i]][-1] += 1
	ans = 0
	for i in range(200):
		if not sl[i]:
			continue
		if len(sl[i]) == 1:
			ans = max(ans, 1)
			continue
		for j in range(len(sl[i]) // 2):
			le = sl[i][j]
			ri = sl[i][-1 - j]
			for k in range(200):
				if i == k:
					ans = max(ans, len(sl[i]))
					continue
				if sl[k]:
					ans = max(ans, 2 * (j + 1) + ss[k][ri] - ss[k][le])
	print(ans)


import sys
input = sys.stdin.readline
from math import *
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = [int(x) for x in input().split()]
	ff = [{} for i in range(27)]
	fl = [{} for i in range(27)]
	count = [0 for i in range(27)]
	cal = [[0 for i in range(27)] for i in range(n + 1)]
	for i in range(n):
		for j in range(27):
			if i == 0:
				cal[i][j] = int(a[i] == j)
			else:
				cal[i][j] = cal[i - 1][j] + int(a[i] == j)
	for i in range(n):
		count[a[i]] += 1
		ff[a[i]][count[a[i]]] = i
	count = [0 for i in range(27)]
	for i in range(n - 1, -1, -1):
		count[a[i]] += 1
		fl[a[i]][count[a[i]]] = i
	maxi = 1
	for i in range(1, 27):
		for j in ff[i]:
			l = ff[i][j]
			if j not in fl[i]:
				maxi = max(maxi, j)
				continue
			r = fl[i][j]
			c = 2 * j
			g = 0
			for k in range(1, 27):
				if r - 1 < l:
					continue
				g = cal[r - 1][k] - cal[l][k]
				maxi = max(maxi, c + g)
	print(maxi)


from collections import Counter
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	st = set(l)
	dc = Counter(l)
	ma = 0
	for t in dc:
		ma = max(ma, dc[t])
	dp = [[0 for tg in range(n + 1)] for ty in range(201)]
	pos = [[] for pl in range(201)]
	for i in range(1, 201):
		for j in range(1, n + 1):
			dp[i][j] = dp[i][j - 1]
			if l[j - 1] == i:
				pos[i].append(j)
				dp[i][j] += 1

	def getto(x, s1, e1):
		return dp[x][e1] - dp[x][s1 - 1]

	def max_X(ss, ee):
		aq = 0
		for ft in st:
			aq = max(aq, getto(ft, ss, ee))
		return aq
	ans = 0
	for i in st:
		for t in range(len(pos[i]) // 2):
			u = pos[i][t] + 1
			v = pos[i][-(t + 1)] - 1
			z = max_X(u, v)
			ans = max(ans, z + 2 * (t + 1))
	print(max(ans, ma))


from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	graph = defaultdict(list)
	for i in range(n):
		graph[arr[i]].append(i)
	uni = list(set(arr))
	final = set()
	final.add(1)
	for i in uni:
		cur = i
		(l, r) = (0, len(graph[cur]) - 1)
		if len(graph[cur]) >= 2:
			final.add(2)
		cnt = 2
		while l < r:
			(low, high) = (graph[cur][l], graph[cur][r])
			d = defaultdict(int)
			for j in range(low + 1, high):
				if j < n:
					d[arr[j]] += 1
			ans = -1
			for j in d:
				ans = max(ans, d[j])
			final.add(cnt + ans)
			l += 1
			r -= 1
			cnt += 2
	final = list(final)
	print(max(final))


from sys import stdin, stdout
from math import *
input = stdin.readline
for i in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	d1 = []
	d2 = []
	for i in range(n):
		d1.append([0] * 27)
		d2.append([0] * 27)
	d1[0][ar[0]] += 1
	for i in range(1, n):
		for j in range(27):
			d1[i][j] = d1[i - 1][j]
		d1[i][ar[i]] += 1
	d2[-1][ar[-1]] += 1
	for i in range(n - 2, -1, -1):
		for j in range(27):
			d2[i][j] = d2[i + 1][j]
		d2[i][ar[i]] += 1
	ans = 1
	for i in range(n):
		for j in range(i + 1, n):
			a = [0] * 27
			b = [0] * 27
			for k in range(27):
				x = d1[i][k]
				y = d2[j][k]
				a[k] = min(x, y) * 2
				b[k] = d1[j - 1][k] - d1[i][k]
			if ans < max(a) + max(b):
				ans = max(a) + max(b)
	print(ans)


from collections import defaultdict
import heapq

def main():
	t = int(input())
	while t:
		t -= 1
		n = int(input())
		a = list(map(int, input().split()))
		cnt = [[0 for _ in range(n + 1)] for _ in range(26)]
		for i in range(n):
			for j in range(26):
				cnt[j][i + 1] = cnt[j][i]
			cnt[a[i] - 1][i + 1] += 1
		ans = 0
		for i in range(26):
			ans = max(ans, cnt[i][n - 1])
		for l in range(n):
			for r in range(l, n):
				(maxout, maxin) = (0, 0)
				for i in range(26):
					maxout = max(maxout, min(cnt[i][l], cnt[i][n] - cnt[i][r + 1]) * 2)
					maxin = max(maxin, cnt[i][r + 1] - cnt[i][l])
				ans = max(ans, maxout + maxin)
		print(ans)
main()


from collections import Counter

def solve(new):
	ans = 0
	x = 0
	cnt = Counter(new)
	y = cnt[1]
	i = 0
	j = len(new) - 1
	while i < j:
		if new[i] == 0:
			if new[j] == 0:
				x += 1
				i += 1
				j -= 1
			else:
				y -= 1
				j -= 1
		else:
			y -= 1
			i += 1
		ans = max(ans, 2 * x + y)
	return ans

def ri():
	return int(input())

def rl():
	return list(map(int, input().split()))
t = ri()
for _ in range(t):
	n = ri()
	numbers = rl()
	cnt = Counter(numbers)
	ans = 0
	for a in cnt.keys():
		for b in cnt.keys():
			if a == b:
				ans = max(cnt[a], ans)
			else:
				new = []
				for i in numbers:
					if i == a:
						new.append(0)
					if i == b:
						new.append(1)
				ans = max(ans, solve(new))
	print(ans)


from sys import stdin
from collections import Counter
input = stdin.buffer.readline
T = int(input())
for _ in range(T):
	n = int(input())
	ls = list(map(int, input().split()))
	p = [[] for _ in range(27)]
	sm = [[0] * n for _ in range(27)]
	for (i, u) in enumerate(ls):
		p[u].append(i)
	for i in range(1, 27):
		for (j, u) in enumerate(ls):
			if j > 0:
				sm[i][j] += sm[i][j - 1]
			sm[i][j] += i == u

	def max_al(fm, to):
		mx = 0
		for al in range(1, 27):
			mx = max(mx, sm[al][to] - sm[al][fm - 1])
		return mx
	mx = max([len(p[i]) for i in range(1, 27)])
	for al in range(1, 27):
		for i in range(len(p[al]) // 2):
			(fm, to) = (p[al][i] + 1, p[al][-i - 1] - 1)
			almx = max_al(fm, to)
			mx = max(mx, almx + (i + 1) * 2)
	print(mx)


T = int(input())
for t in range(T):
	N = int(input())
	A = list(map(int, input().split()))
	repeats = [[0] * N for _ in range(26)]
	indices = [[] for _ in range(26)]
	for i in range(0, N):
		if i > 0:
			for j in range(26):
				repeats[j][i] = repeats[j][i - 1]
		repeats[A[i] - 1][i] += 1
		indices[A[i] - 1].append(i)
	result = 1
	for i1 in range(len(A)):
		c = repeats[A[i1] - 1][i1]
		i2 = indices[A[i1] - 1][-c]
		if i2 > i1:
			mr = max((repeats[j0][i2 - 1] - repeats[j0][i1] for j0 in range(26)))
			result = max(result, 2 * c + mr)
	print(result)


from collections import defaultdict
import bisect
from sys import stdin
input = stdin.readline

def check(i, j, d):
	maxi = 0
	for k in d:
		k = d[k]
		a = bisect.bisect_right(k, i)
		b = bisect.bisect_left(k, j)
		maxi = max(maxi, b - a)
	return maxi
t = int(input())
for _ in range(t):
	n = int(input())
	A = [int(j) for j in input().split()]
	maxi = 0
	d = defaultdict(list)
	for i in range(n):
		d[A[i]].append(i)
	for k in d:
		k = d[k]
		i = 0
		j = len(k) - 1
		travel = 0
		while i <= j:
			if i == j:
				travel += 1
				maxi = max(maxi, travel)
				break
			a = k[i]
			b = k[j]
			travel += 2
			temp = check(a, b, d)
			maxi = max(maxi, temp + travel)
			i += 1
			j -= 1
	print(maxi)


import sys
import collections
import threading
import string

def sparsetable(a):
	tmp = [0] * 201
	st = []
	for i in range(len(a)):
		tmp[a[i]] += 1
		st.append(tmp[:])
	return st

def func(x, y, st):
	if x >= y:
		return 0
	ans = 0
	for i in range(201):
		ans = max(ans, st[y][i] - st[x][i])
	return ans

def main():
	testn = int(input())
	for _ in range(testn):
		n = int(input())
		a = list(map(int, input().split()))
		d = collections.defaultdict(list)
		st = sparsetable(a)
		for i in range(n):
			d[a[i]].append(i)
		ans = 1
		for key in d:
			z = len(d[key])
			l = d[key]
			for i in range(z // 2):
				ans = max(ans, (i + 1) * 2 + func(l[i], l[z - 1 - i] - 1, st))
		print(ans)
input = sys.stdin.readline
main()


import sys
input = sys.stdin.buffer.readline

def prog():
	for _ in range(int(input())):
		n = int(input())
		nums = list(map(int, input().split()))
		sums = []
		possible = set(nums)
		lengths = [1]
		psums = [[0] for i in range(201)]
		indexes = [[] for i in range(201)]
		for i in range(n):
			indexes[nums[i]].append(i)
			for j in possible:
				psums[j].append(psums[j][-1] + (j == nums[i]))
		for a in possible:
			for x in range(1, len(indexes[a]) // 2 + 1):
				start = indexes[a][x - 1] + 1
				end = indexes[a][len(indexes[a]) - x] - 1
				max_mid = 0
				for b in possible:
					max_mid = max(max_mid, psums[b][end + 1] - psums[b][start])
				lengths.append(2 * x + max_mid)
		sys.stdout.write(str(max(lengths)) + '\n')
prog()


def compute(a, b, isAdd=True):
	ans = [0] * len(a)
	for i in range(0, len(a)):
		if isAdd:
			ans[i] = a[i] + b[i]
		else:
			ans[i] = a[i] - b[i]
	return ans

def solve(arr):
	n = len(arr)
	if n == 0:
		print(0)
		return
	distinctElements = list(set(arr))
	d = len(distinctElements)
	mapElementToIndex = {}
	for i in range(0, d):
		mapElementToIndex[distinctElements[i]] = i
	totalFre = [0] * d
	for i in range(0, len(arr)):
		totalFre[mapElementToIndex[arr[i]]] += 1
	presentCount = [0] * d
	rigthIndex = [n] * d
	rightFre = [[0] * d for i in range(0, d)]
	leftFre = [0] * d
	finalAns = 0
	for i in range(0, n):
		index = mapElementToIndex[arr[i]]
		leftFre[index] += 1
		r = rigthIndex[index]
		for j in range(r - 1, i, -1):
			if arr[j] == arr[i]:
				rigthIndex[index] = j
				presentCount[index] += 1
				rightFre[index][index] += 1
				inbetweenFre = compute(totalFre, compute(leftFre, rightFre[index]), False)
				ans = 2 * presentCount[index] + max(inbetweenFre)
				finalAns = max(ans, finalAns)
				break
			else:
				rightFre[index][mapElementToIndex[arr[j]]] += 1
	print(max(1, finalAns))
t = int(input())
for i in range(0, t):
	input()
	arr = list(map(lambda x: int(x), input().split()))
	solve(arr)


from bisect import bisect_left
for x in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for i in range(n):
		if a[i] in d:
			d[a[i]].append(i)
		else:
			d[a[i]] = [i]
	ma = 0
	for i in d.keys():
		for j in d.keys():
			if i != j:
				for k in range(1, len(d[i]) // 2 + 1):
					ma = max(ma, 2 * k - bisect_left(d[j], d[i][k - 1]) + bisect_left(d[j], d[i][-k]))
	for i in d.keys():
		ma = max(ma, len(d[i]))
	print(ma)
a = []
for i in range(10000):
	a.append(i)


for _ in range(int(input())):
	n = int(input())
	a = [int(i) - 1 for i in input().split(' ')]
	dp = [[0 for i in range(200)] for i in range(n)]
	for i in range(n):
		for j in range(200):
			dp[i][j] = dp[i - 1][j]
		dp[i][a[i]] += 1
	m = 1
	for i in range(200):
		(s, e, c) = (0, n - 1, 0)
		while s < e:
			while s < e and a[s] != i:
				s += 1
			while s < e and a[e] != i:
				e -= 1
			if s < e:
				c += 2
				for j in range(200):
					m = max(m, c + dp[e - 1][j] - dp[s][j])
				s += 1
				e -= 1
	print(m)


def r(a, b):
	n = len(a)
	s = len(a) // 2
	j = s - 1
	v = -1
	while j >= 0:
		x = a[j]
		y = a[n - 1 - j]
		c = b[y] - b[x + 1]
		s = 2 * (j + 1) + c
		if s > v:
			v = s
		j += -1
	return v
t = int(input())
for i in range(t):
	n = int(input())
	b = list(map(int, input().split()))
	a = []
	c = dict()
	for j in range(1, 201):
		c[j] = 0
	for j in range(202):
		a.append([])
	for j in range(n):
		a[b[j]].append(j)
		c[b[j]] = 1
	pre = [[0] for i in range(201)]
	for i in range(1, 201):
		if c[i] == 1:
			y = a[i]
			d = dict()
			for j in y:
				d[j] = 1
			j = 0
			while j < n:
				if j in d.keys():
					pre[i].append(pre[i][-1] + 1)
				else:
					pre[i].append(pre[i][-1])
				j += 1
	m = -1
	d = []
	for j in range(1, 201):
		if c[j] == 1:
			d.append(j)
	for j in d:
		for p in d:
			if p == j:
				h = len(a[p])
			else:
				h = r(a[j], pre[p])
			if h > m:
				m = h
	print(m)


from collections import Counter
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = Counter(a)
	b = list(b)
	m = len(b)
	rui = [[0] * m for i in range(n + 1)]
	for i in range(n):
		for j in range(m):
			if a[i] == b[j]:
				rui[i + 1][j] = rui[i][j] + 1
			else:
				rui[i + 1][j] = rui[i][j]
	ans = 0
	for i in range(n):
		for j in range(i, n):
			cmax = 0
			dmax = 0
			cur = 0
			for k in range(m):
				q = rui[j + 1][k] - rui[i][k]
				r = min(rui[i][k], rui[n][k] - rui[j + 1][k])
				cmax = max(cmax, q)
				dmax = max(dmax, r)
			ans = max(ans, cmax + dmax * 2)
	print(ans)


import sys
import bisect
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	cnt_pre = [[] for i in range(27)]
	sc = [[0] * (n + 1) for i in range(27)]
	for i in range(n):
		cnt_pre[a[i]].append(i + 1)
		sc[a[i]][i + 1] += 1
	for i in range(27):
		for j in range(1, n + 1):
			sc[i][j] += sc[i][j - 1]
	ans = 0
	for i in range(27):
		ans = max(ans, sc[i][-1])
	for i in range(27):
		l = len(cnt_pre[i])
		for x in range(1, l // 2 + 1):
			left = cnt_pre[i][x - 1]
			right = cnt_pre[i][l - x]
			for j in range(27):
				if i == j:
					continue
				ans = max(ans, 2 * x + sc[j][right] - sc[j][left - 1])
	print(ans)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import sys
from collections import defaultdict

def solve(n, A):
	if n == 1:
		return 1
	if n == 2:
		if len(set(A)) == 1:
			return 2
		return 1
	L = [[0] * 27 for _ in range(n + 1)]
	for (i, a) in enumerate(A):
		for j in range(27):
			L[i + 1][j] = L[i][j]
		L[i + 1][a] += 1
	ans = 0
	for l in range(n):
		for r in range(l, n):
			(Left, Right) = ([0] * 27, [0] * 27)
			mid = 0
			for i in range(27):
				Left[i] = L[l][i]
				mid = max(mid, L[r + 1][i] - L[l][i])
				Right[i] = L[n][i] - L[r + 1][i]
			tmp = 0
			for i in range(27):
				tmp = max(tmp, min(Left[i], Right[i]))
			ans = max(ans, mid + tmp * 2)
	return ans

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		A = tuple(map(int, input().split()))
		ans = solve(n, A)
		sys.stdout.write(str(ans) + '\n')
main()


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import time
start_time = time.time()
import collections as col
import math, string
from functools import reduce

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def solve():
	N = getInt()
	A = getInts()
	A = [A[i] - 1 for i in range(N)]
	dp = [[0 for j in range(201)] for i in range(N + 1)]
	pos = [[] for j in range(201)]
	for i in range(N):
		for j in range(201):
			dp[i + 1][j] = dp[i][j]
		dp[i + 1][A[i]] += 1
		pos[A[i]].append(i)
	ans = 0
	for i in range(201):
		ans = max(ans, len(pos[i]))
		for j in range(len(pos[i]) // 2):
			l = pos[i][j] + 1
			r = pos[i][len(pos[i]) - j - 1] - 1
			for k in range(201):
				x = dp[r + 1][k] - dp[l][k]
				ans = max(ans, (j + 1) * 2 + x)
	return ans
for _ in range(getInt()):
	print(solve())


def solve():
	n = int(input())
	a = list(map(int, input().split()))
	d = {i: [] for i in range(1, 26 + 1)}
	ac = [0 for i in range(26 + 1)]
	ach = []
	for (i, ai) in enumerate(a):
		d[ai].append(i)
		ac[ai] += 1
		ach.append(ac.copy())
	maxs = max(ac)
	for i in range(1, 26 + 1):
		j = 0
		pos = d[i]
		k = len(pos) - 1
		while j < k:
			x = ach[pos[j]]
			y = ach[pos[k]]
			for l in range(len(x)):
				y[l] -= x[l]
			y[i] -= 1
			maxs = max(maxs, max(y) + (j + 1) * 2)
			j += 1
			k -= 1
	print(maxs)

def main():
	t = int(input())
	for _ in range(t):
		solve()
main()


T = int(input())
Q = []
for t in range(T):
	N = int(input())
	A = [int(_) for _ in input().split()]
	Q.append((N, A))
R = []
for (N, A) in Q:
	prefC = [[0] * 26 for _ in range(N + 1)]
	for c in range(26):
		for i in range(N):
			prefC[i + 1][c] = prefC[i][c]
			if A[i] == c + 1:
				prefC[i + 1][c] += 1
	answer = 0
	for l in range(N):
		for r in range(l, N):
			cntin = 0
			for c in range(26):
				cntin = max(cntin, prefC[r + 1][c] - prefC[l][c])
			cntout = 0
			for c in range(26):
				cntout = max(cntout, min(prefC[l][c], prefC[N][c] - prefC[r + 1][c]))
			answer = max(answer, 2 * cntout + cntin)
	R.append(answer)
print('\n'.join(map(str, R)))


for f in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for i in a:
		d[i] = d.get(i, 0) + 1
	ans = 0
	d1 = {}
	for i in range(n):
		if d1.get(a[i], 0) + 1 <= d[a[i]] // 2:
			maxx = 0
			d2 = {}
			d1[a[i]] = d1.get(a[i], 0) + 1
			x = d1[a[i]]
			j = i + 1
			while d[a[i]] - d2.get(a[i], 0) - d1[a[i]] >= x:
				if a[i] == a[j]:
					d2[a[i]] = d2.get(a[i], 0) + 1
				else:
					d2[a[j]] = d2.get(a[j], 0) + 1
					maxx = max(maxx, d2[a[j]])
				j += 1
			ans = max(ans, maxx + 2 * x)
		else:
			ans = max(ans, d[a[i]])
	print(ans)


numbers = 26
for _ in range(int(input())):
	n = int(input())
	seq = [int(x) - 1 for x in input().split()]
	pre = [(n + 1) * [0] for i in range(numbers)]
	for (j, val) in enumerate(seq, 1):
		for i in range(numbers):
			if val == i:
				pre[i][j] = pre[i][j - 1] + 1
			else:
				pre[i][j] = pre[i][j - 1]
	ans = 1
	for i in range(numbers):
		max_val = pre[i][-1] // 2
		for x in range(1, 1 + max_val):
			bmin = pre[i].index(x)
			bmax = n + 1 - pre[i][::-1].index(pre[i][-1] - x)
			ymax = 0
			if bmax - bmin > 1:
				for j in range(numbers):
					ymax = max(ymax, pre[j][bmax - 1] - pre[j][bmin])
			ans = max(ans, ymax + 2 * x)
	print(ans)


import sys
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]
for _ in range(int(ri())):
	n = int(ri())
	a = Ri()
	count = list2d(27, len(a) + 1, 0)
	for i in range(len(a)):
		for j in range(1, 27):
			count[j][i + 1] = count[j][i]
		count[a[i]][i + 1] += 1
	ans = -1
	for i in range(len(a)):
		for j in range(i + 1, len(a)):
			if a[i] == a[j]:
				left = count[a[i]][i + 1]
				right = count[a[i]][len(a)] - count[a[i]][j]
				maxx = 0
				for k in range(1, 27):
					if k != a[i]:
						cnt = count[k][j + 1] - count[k][i]
						maxx = max(maxx, cnt)
				ans = max(ans, min(left, right) * 2 + maxx)
	for i in range(1, 27):
		ans = max(ans, count[i][n])
	print(ans)


import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	for _ in range(II()):
		n = II()
		aa = LI()
		cs = [[0] for _ in range(26)]
		for a in aa:
			for i in range(26):
				cs[i].append(cs[i][-1])
			cs[a - 1][-1] += 1
		ans = 0
		for l in range(n):
			for r in range(l + 1, n + 1):
				x = y = -1
				for i in range(26):
					csi = cs[i]
					cur = min(csi[l], csi[n] - csi[r])
					if cur > x:
						x = cur
					cur = csi[r] - csi[l]
					if cur > y:
						y = cur
				ans = max(ans, x * 2 + y)
		print(ans)
main()


from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect

def LI():
	return [int(x) for x in sys.stdin.readline().split()]

def I():
	return int(sys.stdin.readline())

def LS():
	return [list(x) for x in sys.stdin.readline().split()]

def S():
	res = list(sys.stdin.readline())
	if res[-1] == '\n':
		return res[:-1]
	return res

def IR(n):
	return [I() for i in range(n)]

def LIR(n):
	return [LI() for i in range(n)]

def SR(n):
	return [S() for i in range(n)]

def LSR(n):
	return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():

	def f(a, b):
		if a == b:
			return len(d[a])
		da = d[a]
		db = d[b]
		res = 0
		for x in range(len(da) >> 1):
			l = da[x]
			r = da[-1 - x]
			i = bisect.bisect_left(db, l)
			j = bisect.bisect_left(db, r)
			y = max(0, j - i)
			s = 2 * (x + 1) + y
			if res < s:
				res = s
		return res
	t = I()
	for _ in range(t):
		n = I()
		a = LI()
		m = max(a)
		d = [[] for i in range(m)]
		for i in range(n):
			ai = a[i] - 1
			d[ai].append(i)
		ans = 1
		for a in range(m):
			if not d[a]:
				continue
			for b in range(m):
				if not d[b]:
					continue
				res = f(a, b)
				if ans < res:
					ans = res
		print(ans)
	return

def __starting_point():
	solve()
__starting_point()


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	m = 0
	l1 = [0] * 26
	for j in range(len(l1)):
		l1[j] = [0] * n
	for j in range(n):
		l1[l[j] - 1][j] += 1
	for j in range(26):
		for k in range(1, n):
			l1[j][k] += l1[j][k - 1]
	for j in range(1, 27):
		for k in range(1, 27):
			if l1[k - 1][n - 1] == 0 and l1[j - 1][n - 1] == 0:
				continue
			if j == k:
				m = max(m, l1[k - 1][n - 1])
				continue
			m = max(m, l1[k - 1][n - 1])
			a = 0
			b = n - 1
			v = 0
			while a < b:
				if v != 0:
					a += 1
					b -= 1
				while a < n and l[a] != j:
					a += 1
				while b >= 0 and l[b] != j:
					b -= 1
				v += 1
				if a == n or b == -1:
					break
				if a >= b:
					break
				m = max(m, 2 * v + l1[k - 1][b] - l1[k - 1][a])
	print(m)


import sys, os, io
for _ in range(int(input())):
	n = int(input())
	a = [int(i) - 1 for i in input().split()]
	cnt = [[0] * n for i in range(26)]
	ind = [[] for i in range(26)]
	for i in range(n):
		cnt[a[i]][i] += 1
		ind[a[i]].append(i)
	for i in range(26):
		for j in range(1, n):
			cnt[i][j] += cnt[i][j - 1]
	ans = 0
	for i in range(26):
		l = 0
		r = len(ind[i]) - 1
		tans = 0
		ttans = 0
		while l < r:
			ttans += 2
			for j in range(26):
				ttans += cnt[j][ind[i][r] - 1] - cnt[j][ind[i][l]]
				tans = max(tans, ttans)
				ttans -= cnt[j][ind[i][r] - 1] - cnt[j][ind[i][l]]
			l += 1
			r -= 1
			ans = max(ans, tans)
	for i in range(26):
		ans = max(ans, cnt[i][-1])
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	dp = [[0 for i in range(n + 1)] for j in range(27)]
	for i in range(n):
		dp[a[i]][i + 1] += 1
		for j in range(1, 27):
			dp[j][i + 1] += dp[j][i]
	ans = 1
	for i in range(1, 27):
		l = 0
		r = n - 1
		c = 0
		while l < r:
			while l < r and a[l] != i:
				l += 1
			while l < r and a[r] != i:
				r -= 1
			if l < r and a[l] == i and (a[r] == i):
				m = 0
				for j in range(1, 27):
					m = max(m, dp[j][r] - dp[j][l + 1])
				ans = max(c + m + 2, ans)
				c += 2
				l += 1
				r -= 1
	print(ans)


t = int(input())
for _ in range(t):
	res = 0
	n = int(input())
	a = [int(i) - 1 for i in input().split()]
	(ll, lr) = ([[0] * 201], [[0] * 201])
	ll[0][a[0]] = 1
	lr[0][a[-1]] = 1
	lookup = [[-1] * (n + 1) for i in range(201)]
	c = [0] * 201
	for i in a:
		c[i] += 1
	for i in a[1:]:
		ll.append(ll[-1][:])
		ll[-1][i] += 1
	for i in a[:-1][::-1]:
		lr.append(lr[-1][:])
		lr[-1][i] += 1
	lr = lr[::-1]
	temp = [0] * 201
	for i in range(n - 1, -1, -1):
		temp[a[i]] += 1
		lookup[a[i]][temp[a[i]]] = i
	res = max(temp)
	for i in range(201):
		for j in range(n):
			v = ll[j][i]
			j2 = lookup[i][v]
			if j2 <= j:
				continue
			tres = 0
			for k in range(201):
				t = c[k] - ll[j][k] - lr[j2][k]
				if tres < t:
					tres = t
			tres += 2 * v
			res = max(res, tres)
	print(res)


from collections import defaultdict
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	d = defaultdict(lambda : [], d)
	k = 0
	for i in a:
		d[i].append(k)
		k += 1
	arr = []
	for i in d.keys():
		if len(d[i]) > 1:
			arr.append(i)
	ans1 = 0
	for i in d.keys():
		if ans1 < len(d[i]):
			ans1 = len(d[i])
	ans = 0
	if len(arr) == 0:
		print(1)
	else:
		for i in arr:
			w = 0
			e = len(d[i]) - 1
			while w < e:
				m1 = d[i][w]
				m2 = d[i][e]
				c = sorted(a[m1 + 1:m2])
				d1 = {}
				d1 = defaultdict(lambda : 0, d1)
				maax = 0
				for q in a[m1 + 1:m2]:
					d1[q] += 1
					if maax < d1[q]:
						maax = d1[q]
				if ans < maax + 2 * (w + 1):
					ans = maax + 2 * (w + 1)
				w += 1
				e -= 1
		print(max(ans, ans1))


import bisect
t = int(input())
num = 200
answers = []
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	prefix = {}
	for i in range(1, num + 1):
		prefix[i] = list()
		prefix[i].append(0)
	for i in range(n):
		for j in range(1, num + 1):
			if arr[i] == j:
				prefix[j].append(prefix[j][-1] + 1)
			else:
				prefix[j].append(prefix[j][-1])
	ans = 0
	for i in range(1, n + 1):
		j = arr[i - 1]
		right = prefix[j][i]
		right_ind = i
		left_ind = bisect.bisect_right(prefix[j], prefix[j][-1] - right) - 1
		if left_ind >= len(prefix[j]):
			left_ind = len(prefix[j]) - 1
		left = prefix[j][-1] - prefix[j][left_ind]
		mid = 0
		for g in range(1, num + 1):
			if prefix[g][left_ind] - prefix[g][right_ind] > mid:
				mid = prefix[g][left_ind] - prefix[g][right_ind]
		if left_ind >= right_ind and 2 * min(right, left) + mid > ans:
			ans = 2 * min(right, left) + mid
		if prefix[j][-1] > ans:
			ans = prefix[j][-1]
	answers.append(str(ans))
print('\n'.join(answers))


from collections import deque

def solve():
	n = int(input())
	li = [int(x) for x in input().split()]
	counts = [[0] * 27]
	pos = [[] for i in range(27)]
	for (i, a) in enumerate(li):
		counts.append(list(counts[-1]))
		counts[-1][a] += 1
		pos[a].append(i)
	mx = 0
	for (i, a) in enumerate(li):
		pre_occur_a = counts[i + 1][a]
		pos_suff_occur_a = pos[a][-pre_occur_a]
		if pos_suff_occur_a > i:
			for b in range(27):
				mx = max(mx, counts[pos_suff_occur_a][b] - counts[i + 1][b] + 2 * pre_occur_a)
		elif pos_suff_occur_a == i:
			mx = max(mx, 2 * pre_occur_a - 1)
	print(mx)
t = int(input())
for i in range(t):
	solve()


def max_len_cal(data, start, end):
	data = list(data)
	counter = 0
	for i in range(len(data)):
		if data[i] >= end:
			break
		elif data[i] > start:
			counter += 1
	return counter
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	index_recorder = dict()
	for j in range(n):
		try:
			index_recorder[a[j]].append(j)
		except:
			index_recorder[a[j]] = [j]
	max_len = 0
	for j in index_recorder.keys():
		counter = 0
		while counter < len(index_recorder[j]) // 2:
			for k in index_recorder.keys():
				max_len = max(max_len, (counter + 1) * 2 + max_len_cal(index_recorder[k], index_recorder[j][counter], index_recorder[j][-counter - 1]))
			counter += 1
	print(max(1, max_len))


def max_pos(ar, a, b, counts):
	ans = 0
	i = 0
	j = len(ar) - 1
	alen = 0
	while i < j:
		if ar[i] == a:
			while i < j and ar[j] != a:
				j -= 1
			j -= 1
			if j >= i:
				alen += 2
			curr_ans = alen + counts[b][j] - counts[b][i]
			ans = max(ans, curr_ans)
		i += 1
	return ans

def solve(ar):
	counts = [[0] * len(ar) for i in range(202)]
	counts[ar[0]][0] = 1
	for (i, val) in enumerate(ar[1:], 1):
		for j in range(202):
			if j != val:
				counts[j][i] = counts[j][i - 1]
			else:
				counts[j][i] = counts[j][i - 1] + 1
	ans = 0
	for i in range(1, 201):
		for j in range(1, 201):
			if counts[i][-1] and counts[j][-1]:
				ans = max(ans, max_pos(ar, i, j, counts))
	return ans
t = int(input())
for _ in range(t):
	n = int(input())
	ar = list(map(int, input().strip().split()))
	if len(ar) == 1:
		print(1)
	else:
		print(solve(ar))


import operator
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	c = dict()
	ans = 1
	for a in range(0, n, 1):
		if arr[a] not in c:
			c[arr[a]] = 0
		c[arr[a]] += 1
		ind = -1
		co = c[arr[a]]
		for b in range(n - 1, a + 1, -1):
			if arr[b] == arr[a]:
				co -= 1
			if co == 0:
				ind = b
				break
		ans = max(ans, c[arr[a]])
		if ind != -1:
			d = dict()
			for e in range(a + 1, b, 1):
				if arr[e] not in d:
					d[arr[e]] = 0
				d[arr[e]] += 1
			temp = 0
			if max(d, key=d.get) in d:
				temp = d[max(d, key=d.get)] + 2 * c[arr[a]]
			ans = max(ans, temp)
	print(ans)


import sys

def data():
	return sys.stdin.readline().strip()
out = sys.stdout.write

def mdata():
	return map(int, data().split())
from collections import defaultdict as dd
for t in range(int(data())):
	n = int(data())
	A = list(mdata())
	s = set(A)
	m = 1
	for i in s:
		(str, end) = (0, n - 1)
		cnt = 0
		while str < end:
			while str < end:
				if A[str] == i:
					break
				str += 1
			while str < end:
				if A[end] == i:
					break
				end -= 1
			if A[str] == A[end] == i:
				d = dd(int)
				for j in range(str + 1, end):
					d[A[j]] += 1
				a = 2
				if str == end:
					a -= 1
				if len(d.keys()) != 0:
					m = max(m, 2 * cnt + a + max(d.values()))
				else:
					m = max(m, 2 * cnt + a)
			else:
				break
			cnt += 1
			str += 1
			end -= 1
	print(m)


import sys
input = sys.stdin.buffer.readline

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

def mult_input():
	return map(int, input().split())
for nt in range(int(input())):
	n = int(input())
	l = list_input()
	if n == 1:
		print(1)
		continue
	elif n == 2:
		if l[0] == l[1]:
			print(2)
		else:
			print(1)
		continue
	if len(set(l)) == n:
		print(1)
		continue
	counts = [[0 for i in range(n)] for j in range(200)]
	d = {}
	for i in range(1, 201):
		count = 0
		d[i] = {}
		for j in range(n):
			if l[j] == i:
				count += 1
				d[i][count] = j
			counts[i - 1][j] = count
	ans = 0
	for i in range(1, 201):
		for j in range(1, 201):
			start = 0
			end = n - 1
			for k in range(len(d[i]) // 2):
				first = d[i][k + 1]
				second = d[i][counts[i - 1][-1] - k]
				ans = max(ans, 2 * (k + 1) + counts[j - 1][second - 1] - counts[j - 1][first])
	print(ans)


import sys
input = sys.stdin.buffer.readline

def getCnts(j, l, r):
	if l > r:
		return 0
	if l == 0:
		return prefCnt[r][j]
	else:
		return prefCnt[r][j] - prefCnt[l - 1][j]
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	prefCnt = [[0 for _a in range(27)] for _b in range(n)]
	for j in range(1, 27):
		cnts = 0
		for i in range(n):
			if a[i] == j:
				cnts += 1
			prefCnt[i][j] = cnts
	ans = 0
	for outer in range(1, 27):
		outerLen = 0
		l = -1
		r = n
		while l < r:
			for inner in range(1, 27):
				innerLen = getCnts(inner, l + 1, r - 1)
				ans = max(ans, outerLen * 2 + innerLen)
			l += 1
			while l < n and a[l] != outer:
				l += 1
			r -= 1
			while r > -1 and a[r] != outer:
				r -= 1
			outerLen += 1
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	cnt1 = [0] * 27
	cnt = [0] * 27
	ans = 1
	for i in a:
		cnt[i] += 1
	for i in range(n):
		cnt2 = [0] * 27
		for j in range(i, n):
			cnt2[a[j]] += 1
			m = 0
			for k in range(1, 27):
				c = min(cnt1[k], cnt[k] - cnt1[k] - cnt2[k])
				if m < c:
					m = c
			m *= 2
			m += max(cnt2)
			if ans < m:
				ans = m
		cnt1[a[i]] += 1
	print(ans)


t = int(input())
while t:
	t -= 1
	n = int(input())
	v = list(map(int, input().strip().split()))[:n]
	ans = 1
	w = [0] * 26
	w2 = [0] * 26
	for i in range(n):
		v[i] -= 1
		w2[v[i]] += 1
		ans = max(ans, w2[v[i]])
	i = 0
	while i < n:
		j = i + 1
		w[v[i]] += 1
		w4 = [0] * 26
		while j < n:
			w4[v[j]] += 1
			ans = max(ans, 2 * min(w[v[i]], w2[v[i]] - w4[v[i]] - w[v[i]]) + w4[v[j]])
			j += 1
		i += 1
	print(ans)


import sys
input = sys.stdin.readline
MOD = 1000000007
MOD2 = 998244353
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
let = 'abcdefghijklmnopqrstuvwxyz'
for _ in range(ii()):
	n = ii()
	l = il()
	cntr = dict()
	mxcnt = 0
	dp = [[0 for i in range(201)] for j in range(n + 1)]
	for i in range(n - 1, -1, -1):
		for j in range(1, 201):
			dp[i][j] = dp[i + 1][j] + (l[i] == j)
		mxcnt = max(dp[i][l[i]], mxcnt)
		x = str(dp[i][l[i]]) + ',' + str(l[i])
		cntr[x] = i
	cntr2 = dict()
	for i in range(n):
		cntr2[l[i]] = cntr2.get(l[i], 0) + 1
		x = str(cntr2[l[i]]) + ',' + str(l[i])
		if x in cntr and cntr[x] > i:
			for j in range(1, 201):
				mxcnt = max(cntr2[l[i]] * 2 + (dp[i + 1][j] - dp[cntr[x]][j]), mxcnt)
	print(mxcnt)


from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
for _ in range(ii()):
	MxN = 27
	n = ii()
	a = li()
	st = [[] for i in range(MxN)]
	pref = [[0 for i in range(MxN)] for j in range(n + 1)]
	for i in range(1, n + 1):
		st[a[i - 1]].append(i)
		for j in range(1, MxN):
			pref[i][j] = pref[i - 1][j]
		pref[i][a[i - 1]] += 1
	ans = 0
	for i in range(1, MxN):
		ans = max(ans, len(st[i]))
	for i in range(1, MxN):
		sz = len(st[i])
		if sz == 0:
			continue
		for j in range(sz // 2):
			idx1 = st[i][j]
			idx2 = st[i][sz - j - 1]
			mid = 0
			for k in range(1, MxN):
				if i == k:
					continue
				mid = max(mid, pref[idx2][k] - pref[idx1][k])
			ans = max(ans, 2 * (j + 1) + mid)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	l = list(map(lambda x: int(x) - 1, input().split()))
	pref = {i: [] for i in range(26)}
	cnt = [0 for i in range(26)]
	counter = []
	for i in range(n):
		pref[l[i]].append(i)
		cnt[l[i]] += 1
		counter.append(cnt.copy())
	ans = 1
	for i in range(26):
		for j in range(1, cnt[i] // 2 + 1):
			(r, l) = (pref[i][-j], pref[i][j - 1])
			curr = 0
			for x in range(26):
				curr = max(curr, counter[r - 1][x] - counter[l][x])
			ans = max(ans, j * 2 + curr)
	print(ans)


def three_blocks_length(sequence, outer, inner):
	filtered = list(filter(lambda x: x == outer or x == inner, sequence))
	max_length = 0
	outer_indices = []
	inner_indices = []
	for (i, item) in enumerate(filtered):
		if item == outer:
			outer_indices.append(i)
		if item == inner:
			inner_indices.append(i)
	for i in range(len(outer_indices) // 2):
		inner_count = filtered[outer_indices[i]:outer_indices[len(outer_indices) - i - 1]].count(inner)
		max_length = max(max_length, 2 * (i + 1) + inner_count)
	return max_length

def solve(sequence):
	distinct = set(sequence)
	max_length = 0
	for outer in distinct:
		for inner in distinct:
			if outer != inner:
				max_length = max(max_length, three_blocks_length(sequence, outer, inner))
			else:
				max_length = max(max_length, sequence.count(outer))
	return max_length
for i in range(int(input())):
	n = int(input())
	sequence = [int(x) for x in input().split()]
	print(solve(sequence))


from collections import Counter
TC = int(input())
while TC > 0:
	n = int(input())
	a = list(map(int, input().split()))
	ans = Counter(a).most_common()[0][1]
	for x in range(1, 201):
		S = Counter(a)
		i = 0
		j = n - 1
		cnt = 0
		while i < j:
			while i < j:
				S[a[i]] -= 1
				if a[i] == x:
					break
				i += 1
			while i < j:
				S[a[j]] -= 1
				if a[j] == x:
					break
				j -= 1
			if i >= j:
				break
			cnt += 1
			ans = max(ans, S.most_common(1)[0][1] + cnt * 2)
			i += 1
			j -= 1
	print(ans)
	TC -= 1


def threeblock(arr):
	d = {i: [] for i in range(1, 27)}
	for i in range(len(arr)):
		d[arr[i]].append(i)
	ans = 1
	for val in range(1, 27):
		c = 1
		while c * 2 <= len(d[val]):
			l = d[val][c - 1] + 1
			r = d[val][-c]
			middle = [0] * 27
			for pt in range(l, r):
				middle[arr[pt]] += 1
			ans = max(ans, max(middle) + 2 * c)
			c += 1
	return ans
for i in range(int(input())):
	a = input()
	lst = list(map(int, input().strip().split()))
	print(threeblock(lst))


T = int(input())
for t in range(T):
	N = int(input())
	A = [int(_) for _ in input().split()]
	prefC = [[0] * (N + 1) for _ in range(26)]
	for c in range(26):
		for i in range(N):
			prefC[c][i + 1] = prefC[c][i]
			if A[i] == c + 1:
				prefC[c][i + 1] += 1
	answer = 0
	for l in range(N):
		for r in range(l, N):
			cntin = max([prefC[c][r + 1] - prefC[c][l] for c in range(26)])
			cntout = max([min(prefC[c][l], prefC[c][N] - prefC[c][r + 1]) for c in range(26)])
			answer = max(answer, 2 * cntout + cntin)
	print(answer)


for test in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	arr = [[0 for i in range(n + 1)] for j in range(201)]
	for i in range(n):
		arr[a[i]][i + 1] += 1
		for j in range(1, 201):
			arr[j][i + 1] += arr[j][i]
	ans = 1
	for i in range(1, 201):
		l = 0
		r = n - 1
		c = 0
		while l < r:
			while l < r and a[l] != i:
				l += 1
			while l < r and a[r] != i:
				r -= 1
			if l < r and a[l] == i and (a[r] == i):
				m = 0
				for j in range(1, 201):
					m = max(m, arr[j][r] - arr[j][l + 1])
				ans = max(c + m + 2, ans)
				c += 2
				l += 1
				r -= 1
	print(ans)


import sys
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass

def max_freq(l, r):
	d = {}
	for i in range(l, r + 1):
		if arr[i] in d:
			d[arr[i]] += 1
		else:
			d[arr[i]] = 1
	return max(d.values()) if len(d) > 0 else 0

def palin(st, var):
	i = st
	j = n - 1
	match = 0
	stp = -1
	end = -1
	lmax = 0
	while i < j:
		if arr[i] != var:
			i += 1
		elif arr[j] != var:
			j -= 1
		elif arr[i] == arr[j] == var:
			match += 2
			stp = i
			end = j
			i += 1
			j -= 1
			lmax = max(lmax, match + max_freq(i, j))
	return lmax
input = sys.stdin.readline
for tt in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	if n == 1:
		print(1)
		continue
	check = set()
	ans = 0
	for i in range(n):
		if arr[i] not in check:
			check.add(arr[i])
			ans = max(ans, palin(i, arr[i]))
	if ans == 0:
		print(1)
	else:
		print(ans)


def f(l):
	d = {}
	for i in l:
		try:
			d[i] += 1
		except:
			d[i] = 1
	maxm = 0
	for i in d:
		if d[i] > maxm:
			maxm = d[i]
	return maxm
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	m = list(set(l))
	ans = {}
	for i in m:
		ans[i] = 0
	for k in ans:
		i = 0
		j = n - 1
		count = 0
		while i <= j:
			b = 0
			while l[i] != k and i < n:
				i += 1
			while l[j] != k and j >= 0:
				j -= 1
			if i < j and i < n and (j >= 0):
				count += 1
			elif i == j:
				b = 1
			else:
				break
			ans[k] = max(ans[k], b + 2 * count + f(l[i + 1:j]))
			i += 1
			j -= 1
	maxm = 0
	for i in ans:
		if ans[i] > maxm:
			maxm = ans[i]
	print(maxm)


from sys import stdin

def iinput():
	return int(stdin.readline())

def minput():
	return map(int, stdin.readline().split())

def linput():
	return list(map(int, stdin.readline().split()))
from collections import defaultdict
from bisect import bisect
t = iinput()
while t:
	t -= 1
	n = iinput()
	a = linput()
	d = defaultdict(list)
	for i in range(n):
		d[a[i]].append(i)
	ans = 1
	for p in d:
		ans = max(ans, len(d[p]))
		for q in d:
			if p != q:
				for i in range(len(d[p]) // 2):
					x = bisect(d[q], d[p][i])
					y = bisect(d[q], d[p][len(d[p]) - 1 - i])
					if y != x:
						ans = max(ans, y - x + 2 * (i + 1))
	print(ans)


def solve(arr, n, ans):
	dp = [[0 for i in range(27)] for j in range(n)]
	for i in range(n):
		dp[i][arr[i]] += 1
		if i > 0:
			for j in range(27):
				dp[i][j] += dp[i - 1][j]
	max_val = 0
	for i in range(n):
		left = dp[i][:]
		for j in range(i + 1, n):
			total = 0
			counts = dp[j - 1][:]
			for k in range(27):
				counts[k] -= dp[i][k]
			total += max(counts)
			right = dp[-1][:]
			for k in range(27):
				right[k] -= dp[j - 1][k]
			max_curr = 0
			for k in range(27):
				max_curr = max(max_curr, 2 * min(left[k], right[k]))
			total += max_curr
			max_val = max(max_val, total)
		max_val = max(max_val, max(left))
	ans.append(max_val)

def main():
	t = int(input())
	ans = []
	for i in range(t):
		n = int(input())
		arr = list(map(int, input().split()))
		solve(arr, n, ans)
	for i in ans:
		print(i)
main()


t = int(input())
for turn in range(t):
	n = int(input())
	lis = list(map(int, input().split()))
	li = [[] for i in range(26)]
	for i in range(n):
		li[lis[i] - 1].append(i)
	ans = 0
	for i in range(26):
		for j in range(26):
			if i == j:
				ans = max(ans, len(li[i]))
			else:
				for k in range(len(li[i]) // 2):
					left = li[i][k]
					right = li[i][-(k + 1)]
					anss = 2 * (k + 1)
					for num in li[j]:
						if left < num < right:
							anss += 1
					ans = max(ans, anss)
	print(ans)


from collections import defaultdict, Counter
from functools import lru_cache
from heapq import heappush, heappop
from math import gcd, floor, ceil
from sys import stdin, stdout

def ilist():
	return [int(x) for x in stdin.readline().strip().split(' ')]

def iint():
	return int(stdin.readline().strip())

def istr():
	return stdin.readline().strip()

def diff(l2, l1):
	d = [0] * (26 + 1)
	for i in range(len(l1)):
		d[i] = l2[i] - l1[i]
	return d

def solve(a):
	n = len(a)
	count = [[0] * (26 + 1) for _ in range(n + 1)]
	for i in range(n):
		count[i + 1] = count[i][:]
		count[i + 1][a[i]] += 1
	res = max(count[n])
	for i in range(1, n + 1):
		for j in range(i + 1, n):
			l = diff(count[i], count[0])
			m = diff(count[j], count[i])
			r = diff(count[n], count[j])
			outer = 0
			inner = max(m)
			for j in range(1, 26 + 1):
				if l[j] == r[j]:
					outer = max(outer, 2 * l[j])
			res = max(res, outer + inner)
	return res
t = iint()
for _ in range(t):
	n = iint()
	a = ilist()
	print(solve(a))


t = int(input())
for i in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	new_a = []
	now = a[0]
	s = 1
	for i in range(1, n):
		if a[i] == now:
			s += 1
		else:
			new_a.append([now, s])
			s = 1
			now = a[i]
	new_a.append([now, s])
	p = {}
	a = list(set(a))
	for i in range(len(a)):
		p[a[i]] = [0]
	for i in range(len(new_a)):
		for j in p.keys():
			if j == new_a[i][0]:
				p[j].append(p[j][-1] + new_a[i][1])
			else:
				p[j].append(p[j][-1])
	ans = -1
	for i in range(len(new_a)):
		for j in range(i, len(new_a)):
			mx = -1
			good_color = -1
			for k in a:
				counter_color = p[k][j + 1] - p[k][i]
				if counter_color > mx:
					mx = max(mx, counter_color)
					good_color = k
			for k in a:
				first = p[k][i] - p[k][0]
				second = p[k][len(new_a)] - p[k][j + 1]
				ans = max(ans, mx + 2 * min(first, second))
	for i in a:
		ans = max(ans, p[i][-1])
	print(ans)


import math
N = int(input())
for i in range(0, N):
	n = int(input())
	S = input().split()
	P = []
	for i in range(0, n):
		P.append(int(S[i]))
	ans = 0
	for i in range(1, 27):
		for j in range(1, 27):
			templist = []
			if i == j:
				continue
			inumber = 0
			numj = 0
			for k in range(0, n):
				if P[k] == i:
					templist.append([i, numj])
					inumber = inumber + 1
				if P[k] == j:
					numj = numj + 1
			best = numj
			for k in range(0, math.floor(inumber / 2)):
				if 2 * (k + 1) + templist[inumber - 1 - k][1] - templist[k][1] > best:
					best = 2 * (k + 1) + templist[inumber - 1 - k][1] - templist[k][1]
			if ans < best:
				ans = best
	print(ans)


import sys
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 998244353
for _ in range(int(ri())):
	n = int(ri())
	a = Ri()
	count = list2d(27, len(a) + 1, 0)
	for i in range(len(a)):
		for j in range(1, 27):
			count[j][i + 1] = count[j][i]
		count[a[i]][i + 1] += 1
	ans = -1
	for i in range(len(a)):
		for j in range(i + 1, len(a)):
			if a[i] == a[j]:
				left = count[a[i]][i + 1]
				right = count[a[i]][len(a)] - count[a[i]][j]
				maxx = 0
				for k in range(1, 27):
					if k != a[i]:
						cnt = count[k][j + 1] - count[k][i]
						maxx = max(maxx, cnt)
				ans = max(ans, min(left, right) * 2 + maxx)
	for i in range(1, 27):
		ans = max(ans, count[i][n])
	print(ans)


from math import ceil, gcd, floor, log
from collections import deque, defaultdict
from heapq import heappush as hpush, heappop as hpop, heapify
from functools import lru_cache
import sys

def inpi():
	return int(input())

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

def inp():
	s = input()
	return list(s)

def inpv():
	return map(int, input().split())
l = 'abcdefghijklmnopqrstuvwxyz'
testcase = int(input())
for test in range(testcase):
	n = inpi()
	a = inpa()
	dp = []
	for (i, j) in enumerate(a):
		if i == 0:
			d = defaultdict(int)
			d[j] += 1
			dp.append(d)
		else:
			d = dp[-1].copy()
			d[j] += 1
			dp.append(d)
	s = set(a)
	m = max(dp[-1].values())
	for x in s:
		for y in s:
			if x != y:
				i = 0
				j = n - 2
				while i <= j:
					c1 = dp[i][x]
					c2 = dp[-1][x] - dp[j][x]
					if c1 == c2:
						k1 = dp[j][y] - dp[i][y]
						m = max(c1 + c2 + k1, m)
					m = max(c1 + c2, m)
					if c1 > c2:
						j -= 1
					elif c2 > c1:
						i += 1
					else:
						i += 1
						j -= 1
	print(m)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for i1 in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = 1
	for i in range(1, 27):
		for j in range(1, 27):
			a = []
			for k in range(n):
				if l[k] == i or l[k] == j:
					a.append(l[k])
			f = 1
			c = 0
			if a == []:
				continue
			ind = []
			for t in range(len(a)):
				if a[t] == i:
					ind.append(t)
				if a[len(a) - 1 - t] == i and t != len(a) - 1 - t:
					ind.append(len(a) - 1 - t)
			ind = list(set(ind))
			ind.sort()
			for t in range(len(ind) // 2):
				s = a[ind[t] + 1:ind[-1 - t]].count(j)
				ans = max(ans, 2 * (t + 1) + s)
	print(ans)


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial, gcd
from collections import deque
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	d = {i: 0 for i in range(1, 27)}
	ans = 0
	for i in l:
		d[i] += 1
		ans = max(ans, d[i])
	z = {i: 0 for i in range(1, 27)}
	for i in range(n):
		z[l[i]] += 1
		t = [0] * 27
		for j in range(i + 1, n):
			t[l[j]] += 1
			if l[i] != l[j]:
				ans = max(ans, 2 * min(z[l[i]], d[l[i]] - z[l[i]] - t[l[i]]) + t[l[j]])
	print(ans)


import sys
import math
from itertools import permutations
input = lambda : sys.stdin.readline().strip()
t = int(input())
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	pre = [[0] * 27 for _ in range(n + 1)]
	st = [[] for _ in range(27)]
	for i in range(1, n + 1):
		st[a[i - 1]].append(i)
		for j in range(1, 27):
			pre[i][j] = pre[i - 1][j]
		pre[i][a[i - 1]] += 1
	ans = 0
	for i in range(1, 27):
		sz = len(st[i])
		ans = max(ans, sz)
		for j in range(sz // 2):
			idx1 = st[i][j]
			idx2 = st[i][sz - 1 - j]
			mid = 0
			for k in range(1, 27):
				if i == k:
					continue
				mid = max(mid, pre[idx2][k] - pre[idx1][k])
			ans = max(ans, 2 * (j + 1) + mid)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	P = [[] for _ in range(27)]
	S = set(A)
	for (i, a) in enumerate(A):
		P[a].append(i)
	ans = 0
	for a in S:
		for i in range(0, len(P[a]) // 2):
			minp = P[a][i]
			maxp = P[a][-(1 + i)]
			s = 0
			for b in S:
				if a == b:
					continue
				s = max(s, sum([p > minp and p < maxp for p in P[b]]))
			ans = max(ans, (i + 1) * 2 + s)
	ans = max(ans, max([len(p) for p in P]))
	print(ans)


import bisect
import collections
import copy
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import List
sys.setrecursionlimit(99999)
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	d = [[] for _ in range(27)]
	for (i, c) in enumerate(arr):
		d[c].append(i)
	ans = 1
	for l in d:
		ans = max(ans, len(l))
		if len(l) > 1:
			i = 0
			j = len(l) - 1
			b = 0
			while i < j:
				b += 2
				for k in d:
					if k != l:
						ans = max(ans, b + bisect.bisect_left(k, l[j]) - bisect.bisect_left(k, l[i] + 1))
				i += 1
				j -= 1
	print(ans)


from sys import stdin
input = stdin.readline

def answer():
	prefix = [[0 for i in range(n + 1)] for j in range(26 + 1)]
	for i in range(1, n + 1):
		for j in range(1, 26 + 1):
			prefix[j][i] = prefix[j][i - 1]
		prefix[a[i - 1]][i] += 1
	ans = 1
	for x in range(1, 26 + 1):
		(i, j, v1, v2) = (0, n - 1, 0, 0)
		while i < j:
			v1 = prefix[x][i + 1]
			while i < j and v1 != v2:
				v2 = prefix[x][n] - prefix[x][j]
				j -= 1
			if i > j:
				break
			value = 0
			for v in range(1, 26 + 1):
				value = max(value, prefix[v][j + 1] - prefix[v][i + 1])
			ans = max(ans, v1 + v2 + value)
			i += 1
	return ans
for T in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	print(answer())


import sys, bisect
from collections import defaultdict
input = sys.stdin.readline

def inp():
	return int(input().rstrip())

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

def insr():
	s = input().rstrip()
	return s[:len(s) - 1]

def invr():
	return map(int, input().rstrip().split())
t = inp()
for _ in range(t):
	n = inp()
	nums = inlt()
	if n == 1:
		print(1)
	elif n == 2:
		if len(set(nums)) == 1:
			print(2)
		else:
			print(1)
	else:
		ans = 1
		for i in range(1, 27):
			left = 0
			right = n - 1
			cnt = 0
			while left < right:
				mid = defaultdict(int)
				if nums[left] == i:
					while left < right:
						if nums[right] == i:
							cnt += 2
							for j in range(left + 1, right):
								mid[nums[j]] += 1
							cur_max = 0
							for key in mid:
								if mid[key] > cur_max:
									cur_max = mid[key]
							ans = max(ans, cnt + cur_max)
							right -= 1
							break
						else:
							right -= 1
				left += 1
		print(ans)


t = int(input())
u = 0
while u < t:
	n = int(input())
	a = list(map(int, input().split()))
	rama = [[0] * n for i in range(27)]
	sita = [[] for i in range(27)]
	for i in range(n):
		if i > 0:
			s = a[i]
			for j in range(27):
				if j == s:
					rama[a[i]][i] = rama[a[i]][i - 1] + 1
					sita[a[i]].append(i)
				else:
					rama[j][i] = rama[j][i - 1]
		else:
			rama[a[i]][i] += 1
			sita[a[i]].append(i)
	result = 0
	for i in range(n):
		d = rama[a[i]][i]
		e = sita[a[i]][-d]
		if e > i:
			maxi = 0
			for j in range(27):
				maxi = max(maxi, rama[j][e - 1] - rama[j][i])
				result = max(2 * d + maxi, result)
	if result == 0:
		print('1')
	else:
		print(result)
	u += 1


def R():
	return map(int, input().split())

def I():
	return int(input())

def S():
	return str(input())

def L():
	return list(R())
from collections import Counter
import math
import sys
from itertools import permutations
import bisect
for _ in range(I()):
	n = I()
	a = L()
	bef = [0] * 27
	aft = [0] * 27
	for i in range(27):
		bef[i] = [0] * n
		aft[i] = [0] * (n + 1)
	bef[a[0]][0] = 1
	for i in range(1, n):
		for k in range(1, 27):
			bef[k][i] = bef[k][i - 1]
		bef[a[i]][i] += 1
	for i in range(n - 1, -1, -1):
		for k in range(1, 27):
			aft[k][i] = aft[k][i + 1]
		aft[a[i]][i] += 1
	ans = 0
	for i in range(n):
		ans = max(ans, aft[a[i]][0])
		for j in range(i, n):
			for k in range(1, 27):
				if i >= 1:
					ans = max(ans, 2 * min(bef[k][i - 1], aft[k][j + 1]) + aft[a[i]][i] - aft[a[i]][j + 1])
	print(ans)


import bisect
t = int(input())
for _ in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	B = {}
	for i in range(n):
		try:
			B[A[i]].append(i)
		except:
			B[A[i]] = [i]
	fa = 0
	flag = 0
	for i in B.keys():
		flag = flag + 1
		lv = len(B[i])
		mv = lv
		for j in range(lv // 2):
			for k in B.keys():
				if k != i:
					c = 2 * (j + 1) + bisect.bisect(B[k], B[i][lv - j - 1]) - bisect.bisect(B[k], B[i][j])
					if mv < c:
						mv = c
		if fa < mv:
			fa = mv
	if flag == 1:
		print(n)
	else:
		print(max(fa, 1))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 1000000007
INF = float('inf')

def main():
	for _ in range(N()):
		n = N()
		arr = list(RL())
		sm = [[0] * 27]
		for i in arr:
			now = sm[-1].copy()
			now[i] += 1
			sm.append(now)
		res = 0
		for i in range(n):
			for j in range(i, n):
				pre = sm[i]
				ind = [sm[j + 1][ii] - sm[i][ii] for ii in range(27)]
				suf = [sm[-1][ii] - sm[j + 1][ii] for ii in range(27)]
				mp = 0
				for k in range(1, 27):
					mp = max(mp, min(pre[k], suf[k]))
				res = max(res, max(ind) + mp * 2)
		print(res)
main()


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def leftBinarySearch(arr, l, r, x):
	temp = -1
	while l <= r:
		mid = (l + r) // 2
		if arr[mid] < x:
			temp = mid
			l = mid + 1
		else:
			r = mid - 1
	return temp

def rightBinarySearch(arr, l, r, x):
	temp = -1
	while l <= r:
		mid = (l + r) // 2
		if arr[mid] > x:
			temp = mid
			r = mid - 1
		else:
			l = mid + 1
	return temp
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	dict1 = {}
	ind = {}
	for i in range(n):
		if arr[i] not in dict1.keys():
			dict1[arr[i]] = 1
			ind[arr[i]] = [i]
		else:
			dict1[arr[i]] += 1
			ind[arr[i]].append(i)
	ans = 0
	for i in dict1.keys():
		ans = max(ans, dict1[i])
	for i in dict1.keys():
		a = dict1[i]
		for j in ind.keys():
			if j != i:
				x = 0
				y = dict1[i] - 1
				for k in range(a // 2):
					ind1 = rightBinarySearch(ind[j], 0, dict1[j] - 1, ind[i][x])
					ind2 = leftBinarySearch(ind[j], 0, dict1[j] - 1, ind[i][y])
					if ind1 != -1 and ind2 != -1 and (ind2 >= ind1):
						ans = max(ans, ind2 - ind1 + 1 + 2 * (x + 1))
					x += 1
					y -= 1
	print(ans)


from sys import stdin
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	d = [[0 for _ in range(26)] for _ in range(n)]
	for i in range(n):
		x = a[i] - 1
		if i != 0:
			for j in range(26):
				d[i][j] = d[i - 1][j]
		d[i][x] += 1
	ans = 1
	for i in range(n):
		for j in range(i, n):
			if a[i] != a[j]:
				continue
			x = a[i] - 1
			for k in range(26):
				if k != x:
					ans = max(d[j][x] - d[i][x] + 1 + 2 * min(d[i][k], d[n - 1][k] - d[j][k]), ans)
	print(ans)


import bisect
for _ in range(int(input())):
	n = int(input())
	a = list(map(lambda x: int(x) - 1, input().split()))
	mxl = 1
	dp = [[0] * len(a) for _ in range(26)]
	for i in range(len(a)):
		for j in range(26):
			dp[j][i] = dp[j][i - 1]
		dp[a[i]][i] += 1
	for i in range(len(a)):
		for j in range(i + 1, len(a)):
			if a[i] == a[j]:
				mxl = max(mxl, dp[a[i]][-1])
				continue
			if dp[a[i]][i] > 0 and dp[a[j]][j] - dp[a[j]][i] > 0 and (dp[a[i]][-1] - dp[a[i]][j] > 0):
				mxl = max(2 * min(dp[a[i]][i], dp[a[i]][-1] - dp[a[i]][j]) + dp[a[j]][j] - dp[a[j]][i], mxl)
	print(mxl)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = set(a)
	m = 1
	dp = [[0] * 201 for i in range(n)]
	for i in range(n):
		for j in range(1, 201):
			dp[i][j] = dp[i - 1][j]
		dp[i][a[i]] += 1
	for i in s:
		(start, end, count) = (0, n - 1, 0)
		while start < end:
			while start < end and a[start] != i:
				start += 1
			while start < end and a[end] != i:
				end -= 1
			if start < end:
				count += 2
				for j in range(1, 201):
					m = max(m, count + dp[end - 1][j] - dp[start][j])
				start += 1
				end -= 1
	print(m)


import sys
input = sys.stdin.readline

def calc(arr, a, b):
	n = len(arr)
	if arr.count(a) <= 1:
		return arr.count(b)
	maxlen = 0
	indices = [i for (i, x) in enumerate(arr) if x == a]
	for i in range(len(indices) // 2):
		idx1 = indices[i]
		idx2 = indices[-i - 1]
		temp = arr[idx1 + 1:idx2]
		maxlen = max(maxlen, (i + 1) * 2 + temp.count(b))
	return maxlen
t = int(input())
for j in range(t):
	n = int(input())
	arr = input().strip().split()
	poss = set(arr)
	maxlen = 0
	for i in poss:
		for j in poss:
			maxlen = max(maxlen, calc(arr, i, j))
	print(maxlen)


import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	n = int(input())
	a = [int(i) - 1 for i in input().split()]
	dp = [[0 for _ in range(200)] for _ in range(n)]
	for i in range(n):
		for j in range(200):
			dp[i][j] = dp[i - 1][j]
		dp[i][a[i]] += 1
	ans = 1
	for i in range(200):
		(l, r, count) = (0, n - 1, 0)
		while l < r:
			while l < r and a[l] != i:
				l += 1
			while l < r and a[r] != i:
				r -= 1
			if l < r:
				count += 2
				for j in range(200):
					ans = max(ans, count + dp[r - 1][j] - dp[l][j])
				l += 1
				r -= 1
	sys.stdout.write(str(ans) + '\n')


import sys
import math
from collections import defaultdict
mod = 1000000007
T = 1
T = int(sys.stdin.readline())
for _ in range(T):
	n = int(input())
	l = list(map(int, input().split()))
	a = []
	d = defaultdict(int)
	ans = 0
	for i in l:
		if d[i] == 0:
			a.append(i)
		d[i] += 1
		if d[i] > ans:
			ans = d[i]
	for i in range(len(a)):
		for j in range(len(a)):
			if i != j:
				m = max(d[a[i]], d[a[j]])
				mm = d[a[i]] >> 1
				y = 0
				for k in range(n):
					if a[i] == l[k]:
						y += 1
						if y > mm:
							break
						t = 0
						q = 0
						for kk in range(k + 1, n):
							if l[kk] == a[j]:
								t += 1
							if l[kk] == a[i]:
								if d[a[i]] - q - y < y:
									break
								ans = max(ans, t + (y << 1))
								q += 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	ans = 0
	d = {}
	for i in l:
		try:
			d[i] += 1
		except:
			d[i] = 1
	for i in range(1, 27):
		e = d.copy()
		a = 0
		b = n - 1
		m = 0
		while a <= b:
			ans = max(m + max(e.values()), ans)
			while a < n and l[a] != i:
				e[l[a]] -= 1
				a += 1
			while b >= 0 and l[b] != i:
				e[l[b]] -= 1
				b -= 1
			m += 2
			if a < n and b >= 0:
				e[l[a]] -= 2
			a += 1
			b -= 1
	print(ans)


T = int(input())
for _ in range(0, T):
	n = int(input())
	s = [int(x) for x in input().split()]
	pre = []
	for i in range(27):
		h = []
		for j in range(n + 1):
			h.append(-1)
		pre.append(h)
	d = [0] * 27
	kk = []
	for i in range(0, len(s)):
		d[s[i]] += 1
		d2 = []
		for j in range(27):
			d2.append(d[j])
		kk.append(d2)
	l = [0] * 27
	for i in range(len(s) - 1, -1, -1):
		l[s[i]] += 1
		pre[s[i]][l[s[i]]] = i
	mx = 1
	for i in range(1, 27):
		for j in range(1, 27):
			for k in range(0, len(s)):
				if s[k] == i:
					ct = kk[k][i]
					fd = pre[i][ct]
					if fd > k:
						ct2 = kk[fd - 1][j] - kk[k][j]
						mx = max(mx, ct + ct + ct2)
	print(mx)


l = ' abcdefghijklmnopqrstuvwxyz'
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = ''.join((l[i] for i in a))
	q = set(s)
	m = 0
	for i in q:
		for j in q:
			if i == j:
				m = max(m, s.count(i))
				continue
			t = ''.join((k for k in s if k == i or k == j))
			for k in range(t.count(i) // 2):
				t = t[t.index(i) + 1:t.rindex(i)]
				m = max(m, t.count(j) + 2 * (k + 1))
	print(m)


import bisect
from collections import defaultdict
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
for _ in range(iinput()):
	n = iinput()
	a = rlinput()
	d = defaultdict(list)
	for i in range(n):
		d[a[i]].append(i)
	ans = 1
	for i in d:
		temp = d[i]
		l = len(temp)
		ans = max(ans, len(temp))
		for j in range(l // 2):
			start = temp[j]
			end = temp[l - j - 1]
			for k in d:
				if k != i:
					tt = d[k]
					val = bisect.bisect(tt, end) - bisect.bisect(tt, start)
					ans = max(ans, val + 2 * (j + 1))
	print(ans)


t = int(input())
for you in range(t):
	n = int(input())
	lpos = [[] for i in range(200)]
	lfi = [[0 for i in range(200)] for j in range(n)]
	l = input().split()
	li = [int(i) for i in l]
	for j in range(200):
		count = 0
		for i in range(n):
			if li[i] == j + 1:
				count += 1
			lfi[i][j] = count
	for i in range(n):
		lpos[li[i] - 1].append(i)
	maxa = 0
	for i in range(200):
		for numofel in range(1, len(lpos[i]) + 1):
			start = lpos[i][numofel - 1] + 1
			end = lpos[i][len(lpos[i]) - numofel] - 1
			if start <= end:
				for k in range(200):
					if k == i:
						continue
					if start == 0:
						if lfi[end][k] + 2 * numofel > maxa:
							maxa = 2 * numofel + lfi[end][k]
					elif lfi[end][k] + 2 * numofel - lfi[start - 1][k] > maxa:
						maxa = 2 * numofel + lfi[end][k] - lfi[start - 1][k]
			else:
				break
		if maxa < len(lpos[i]):
			maxa = len(lpos[i])
	print(maxa)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	int_sum = [[0 for _ in range(27)] for _ in range(n + 1)]
	for i in range(1, n + 1):
		for j in range(1, 27):
			if a[i - 1] == j:
				int_sum[i][j] = int_sum[i - 1][j] + 1
			else:
				int_sum[i][j] = int_sum[i - 1][j]
	ans = 0
	for i in range(n + 1):
		for j in range(i, n + 1):
			(max_a, max_b) = (0, 0)
			for k in range(1, 27):
				max_a = max(max_a, min(int_sum[n][k] - int_sum[j][k], int_sum[i][k]))
				max_b = max(max_b, int_sum[j][k] - int_sum[i][k])
			ans = max(ans, max_a * 2 + max_b)
	print(ans)


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

def mult_input():
	return map(int, input().split())
for nt in range(int(input())):
	n = int(input())
	l = list_input()
	if n == 1:
		print(1)
		continue
	elif n == 2:
		if l[0] == l[1]:
			print(2)
		else:
			print(1)
		continue
	if len(set(l)) == n:
		print(1)
		continue
	counts = [[0 for i in range(n)] for j in range(26)]
	for i in range(1, 27):
		count = 0
		for j in range(n):
			if l[j] == i:
				count += 1
			counts[i - 1][j] = count
	ans = 0
	for i in range(1, 27):
		for j in range(1, 27):
			start = 0
			end = n - 1
			first = 0
			while start < end:
				if l[start] == i and l[end] == i:
					first += 1
					second = counts[j - 1][end - 1] - counts[j - 1][start]
					ans = max(first * 2 + second, ans)
					start += 1
					end -= 1
				elif l[start] == i:
					end -= 1
				elif l[end] == i:
					start += 1
				else:
					end -= 1
					start += 1
	print(ans)


import sys
from array import array
import typing as Tp

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def main():
	t = int(input())
	ans = [0] * t
	acc = [array('i', [0]) * (2 * 10 ** 5 + 1) for _ in range(200)]
	for ti in range(t):
		n = int(input())
		a = (-1,) + tuple(map(lambda x: int(x) - 1, input().split())) + (-1,)
		keys = sorted(set(a[1:-1]))
		for (i, v) in enumerate(a[1:-1], start=1):
			for j in keys:
				acc[j][i] = acc[j][i - 1]
			acc[v][i] += 1
		maxv = max((acc[i][n] for i in keys))
		for x in keys:
			(l, r, outside) = (0, n + 1, 1)
			while l < r:
				while l < r and a[l] != x:
					l += 1
				while l < r and a[r] != x:
					r -= 1
				if l == r:
					break
				inside = 0
				for k in keys:
					inside = max(inside, acc[k][r - 1] - acc[k][l])
				maxv = max(maxv, outside * 2 + inside)
				(l, r, outside) = (l + 1, r - 1, outside + 1)
		ans[ti] = maxv
	sys.stdout.buffer.write(('\n'.join(map(str, ans)) + '\n').encode('utf-8'))
main()


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	u = {k: [0 for i in range(n)] for k in range(1, 27)}
	u[a[0]][0] = 1
	for k in range(1, n):
		for pro in range(1, 27):
			u[pro][k] = u[pro][k - 1]
		u[a[k]][k] = u[a[k]][k - 1] + 1
	maxx = 0
	for pro in range(1, 27):
		cnt = 0
		i = 0
		j = n - 1
		lmax = 0
		while i < n and a[i] != pro:
			i += 1
		while j > -1 and a[j] != pro:
			j -= 1
		if i == j:
			maxx = max(maxx, 1)
		flag = False
		while i < j:
			if a[i] == pro:
				while a[j] != pro:
					j -= 1
					if j == i:
						lmax = max(2 * cnt + 1, lmax)
						flag = True
						break
			if flag:
				break
			flag = False
			if a[j] == pro:
				while a[i] != pro:
					i += 1
					if j == i:
						lmax = max(2 * cnt + 1, lmax)
						flag = True
						break
			if flag:
				break
			if a[i] == pro == a[j]:
				cnt += 1
			mex = 0
			for tro in range(1, 27):
				if tro != pro:
					mex = max(mex, u[tro][j - 1] - u[tro][i])
			lmax = max(mex + 2 * cnt, lmax)
			i += 1
			j -= 1
			if i == j and a[i] == pro:
				lmax = max(lmax, 2 * cnt + 1)
		maxx = max(lmax, maxx)
	print(maxx)


from sys import stdin

def solve(tc):
	n = int(stdin.readline().strip())
	seq = list(map(int, stdin.readline().split()))
	nums = [[] for i in range(200)]
	for i in range(n):
		nums[seq[i] - 1].append(i)
	cum = [[0 for i in range(200)] for j in range(n + 1)]
	for i in range(n):
		cum[i + 1][seq[i] - 1] += 1
		for j in range(200):
			cum[i + 1][j] += cum[i][j]
	ans = 1
	for x in range(200):
		for y in range(200):
			l = 0
			r = len(nums[x]) - 1
			xsize = 2
			while l < r:
				ysize = cum[nums[x][r]][y] - cum[nums[x][l] + 1][y]
				ans = max(ans, xsize + ysize)
				l += 1
				r -= 1
				xsize += 2
	print(ans)
LOCAL_TEST = not __debug__
if LOCAL_TEST:
	infile = __file__.split('.')[0] + '-test.in'
	stdin = open(infile, 'r')
tcs = int(stdin.readline().strip())
tc = 1
while tc <= tcs:
	solve(tc)
	tc += 1


import sys
from array import array
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	s = [int(i) for i in input().split()]
	prev = [array('l', (0 for i in range(n))) for i in range(200)]
	pos = [[] for i in range(200)]
	for i in range(n):
		for j in range(200):
			if i == 0:
				continue
			prev[j][i] = prev[j][i - 1]
		prev[s[i]][i] += 1
		pos[s[i]].append(i)
	ans = 0
	for i in range(200):
		for k in range(200):
			if len(pos[i]):
				ans = max(ans, prev[k][pos[i][-1]] - prev[k][pos[i][0]] + 1)
		for j in range(1, len(pos[i]) // 2 + 1):
			m = 0
			for k in range(200):
				m = max(m, prev[k][pos[i][-j] - 1] - prev[k][pos[i][j - 1]])
			ans = max(ans, m + 2 * j)
	print(ans)


def distribution(n):
	return (n - 1) // 2

def problem_A():
	print(distribution(int(input())))
s = 'abcdefghijklmnopqrstuvwxyz'

def cons_str(n, b):
	a = s[:b]
	ans = ''
	while n > b:
		ans += a
		n -= b
	ans += a[:n]
	return ans

def problem_B():
	(n, a, b) = list(map(int, input().split()))
	print(cons_str(n, b))

def comp_teams(a):
	if len(a) < 2:
		return 0
	s = len(set(a))
	if s == len(a):
		return 1
	a.sort()
	t = 0
	temp = 1
	for i in range(1, len(a)):
		if a[i] == a[i - 1]:
			temp += 1
		else:
			if t < temp:
				t = temp
			temp = 1
	if t < temp:
		t = temp
	if s <= t - 1:
		return s
	if s == t:
		return s - 1
	else:
		return t

def problem_C():
	l = int(input())
	a = list(map(int, input().split()))
	print(comp_teams(a))

def antisudoku(a):
	for i in range(9):
		for j in range(9):
			if a[i][j] == '2':
				a[i][j] = '1'
	return a

def problem_D():
	a = []
	for _ in range(9):
		a.append(list(input()))
	b = antisudoku(a)
	for i in range(9):
		print(''.join(b[i]))

def three_block_palindrome(s):
	a = []
	b = []
	c = []
	l = len(s)
	for _ in range(l):
		a = []
		for _ in range(l + 1):
			a.append([0] * 26)
	l += 1
	for i in range(1, l):
		k = s[i - 1] - 1
		for j in range(26):
			a[i][j] = a[i - 1][j]
		a[i][k] += 1
	maxlength = 0
	for i in range(l):
		for j in range(i, l):
			maxa = 0
			maxb = 0
			for k in range(26):
				if a[l - 1][k] - a[j][k] > a[i][k]:
					if maxa < a[i][k]:
						maxa = a[i][k]
				elif maxa < a[l - 1][k] - a[j][k]:
					maxa = a[l - 1][k] - a[j][k]
				if maxb < a[j][k] - a[i][k]:
					maxb = a[j][k] - a[i][k]
			if maxlength < 2 * maxa + maxb:
				maxlength = 2 * maxa + maxb
	return maxlength

def problem_E1():
	l = int(input())
	s = list(map(int, input().split()))
	print(three_block_palindrome(s))
cases = int(input())
for _ in range(cases):
	problem_E1()


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	m = max(a)
	mem = [[0] * n for i in range(m + 1)]
	position = {}
	for i in range(n):
		if a[i] not in position:
			position[a[i]] = []
		position[a[i]].append(i)
		for j in range(m + 1):
			mem[j][i] = mem[j][i - 1]
		mem[a[i]][i] += 1
	ans = 0
	for i in range(m + 1):
		if i in position:
			ans = max(ans, len(position[i]))
			for p in range(len(position[i])):
				left = position[i][p]
				right = position[i][len(position[i]) - p - 1]
				if left > right:
					break
				max_middle = 0
				for middle in range(m + 1):
					if i == middle:
						continue
					freq = mem[middle][right] - mem[middle][left]
					max_middle = max(max_middle, freq)
				if max_middle != 0:
					ans = max(ans, 2 * (p + 1) + max_middle)
	print(ans)


import sys
lines = sys.stdin.readlines()
T = int(lines[0].strip())
for t in range(T):
	n = int(lines[2 * t + 1].strip())
	nums = list(map(int, lines[2 * t + 2].strip().split(' ')))
	preSum = {}
	kinds = set(nums)
	for k in kinds:
		preSum[k] = [0]
	for num in nums:
		for k in kinds:
			if k == num:
				preSum[k].append(preSum[k][-1] + 1)
			else:
				preSum[k].append(preSum[k][-1])
	maxLen = 0
	for k in kinds:
		maxLen = max(maxLen, preSum[k][-1])
	for k in kinds:
		l = 0
		r = n - 1
		cnt = 0
		while l < r:
			while nums[l] != k:
				l += 1
			while nums[r] != k:
				r -= 1
			if l >= r:
				break
			cnt += 1
			tmpMax = 0
			for p in kinds:
				tmpMax = max(tmpMax, preSum[p][r] - preSum[p][l + 1])
			maxLen = max(maxLen, tmpMax + cnt * 2)
			l += 1
			r -= 1
	print(maxLen)


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	c = [0] * 27
	for x in a:
		c[x] += 1
	res = max(c)
	for l in range(n - 1):
		c = [0] * 27
		for x in a[l:]:
			c[x] += 1
		if c[a[l]] == 1:
			continue
		c[a[l]] = 0
		for r in range(n - 1, l, -1):
			if a[r] == a[l]:
				break
			c[a[r]] -= 1
		(k, t) = (a[l], 0)
		while l < r:
			t += 2
			res = max(res, max(c) + t)
			(l, r) = (l + 1, r - 1)
			while a[l] != k:
				c[a[l]] -= 1
				l += 1
			while a[r] != k:
				c[a[r]] -= 1
				r -= 1
	print(res)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict
from bisect import bisect_left as bis
for j in range(int(input())):
	n = int(input())
	vals = list(map(int, input().split()))
	dict1 = defaultdict(list)
	for s in range(n):
		dict1[vals[s]].append(s)
	lr = []
	maxy = 0
	for s in dict1.keys():
		maxy = max(maxy, len(dict1[s]))
		for b in range(len(dict1[s]) // 2):
			l1 = dict1[s][b]
			l2 = dict1[s][-1 - b]
			lr.append((l1, l2, 2 * (b + 1)))
	for s in range(len(lr)):
		for b in dict1.keys():
			seg = dict1[b]
			l1 = min(bis(seg, lr[s][0]), len(seg) - 1)
			l2 = min(bis(seg, lr[s][1]), len(seg) - 1)
			l2 = max(l2, 0)
			if seg[l2] > lr[s][1]:
				l2 -= 1
			length = l2 + 1 - l1
			if lr[s][0] < seg[l1] and seg[l2] < lr[s][1]:
				maxy = max(maxy, lr[s][2] + length)
	print(maxy)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	count = [0 for _ in range(27)]
	for i in l:
		count[i] += 1
	ans = 1
	for x in set(l):
		r = count[:]
		i = 0
		j = n - 1
		a = 2
		while i < j:
			while i < n and l[i] != x:
				r[l[i]] -= 1
				i += 1
			while j >= 0 and l[j] != x:
				r[l[j]] -= 1
				j -= 1
			if i >= j:
				break
			else:
				r[l[i]] -= 1
				r[l[j]] -= 1
				ans = max(ans, max(r) + a)
				a += 2
				i += 1
				j -= 1
	print(ans)


import sys
import math
import copy
from collections import Counter
debug = 1
readln = sys.stdin.readline

def readint():
	return int(readln().strip())

def readints():
	return map(int, readln().split())

def readstr():
	return readln().strip()

def readstrs():
	return readln().split()

def dbg(*args):
	if debug:
		print(' '.join(map(str, args)))

def subr(i, j, cter):
	if j < i:
		return 0
	elif j == i:
		return 1
	else:
		c = cter[j] - (cter[i - 1] if i > 0 else Counter())
		return c.most_common(1)[0][1]

def solve(n, A):
	maxa = 0
	pos = [[] for _ in range(201)]
	cter = []
	for (i, a) in enumerate(A):
		pos[a].append(i)
		maxa = max(maxa, a)
		if i > 0:
			cter.append(cter[i - 1].copy())
		else:
			cter.append(Counter())
		cter[i][a] += 1
	keys = [a for a in range(len(pos)) if pos[a]]
	ans = 0
	for x in keys:
		posx = pos[x]
		lenx = len(posx)
		for i in range(len(posx) // 2):
			ans = max(ans, (i + 1) * 2 + subr(posx[i] + 1, posx[lenx - i - 1] - 1, cter))
	return max(ans, subr(0, n - 1, cter))
t = readint()
for _ in range(t):
	n = readint()
	A = readints()
	print(solve(n, A))


b = [[0 for i in range(201)] for j in range(200005)]
for _ in range(int(input())):
	(n, a, maximum) = (int(input()), list(map(int, input().split())), 1)
	a = [0] + a
	for x in range(1, n + 1):
		for y in range(1, 201):
			b[x][y] = b[x - 1][y]
		b[x][a[x]] += 1
	s = set(a)
	for i in s:
		(start, end, count) = (1, n, 0)
		while start < end:
			while start < end and a[start] != i:
				start += 1
			while start < end and a[end] != i:
				end -= 1
			if start < end:
				count += 2
				for j in range(1, 201):
					maximum = max(maximum, count + b[end - 1][j] - b[start][j])
				start += 1
				end -= 1
	print(maximum)


from collections import defaultdict
from sys import stdin
input = stdin.readline
for ti in range(int(input().strip())):
	n = int(input())
	a = [int(x) for x in input().strip().split()]
	d = defaultdict(list)
	ans = 0
	cnt = [[0] * (n + 1) for _ in range(201)]
	for i in range(n):
		d[a[i]].append(i)
		for j in range(201):
			cnt[j][i] = cnt[j][i - 1]
		cnt[a[i]][i] += 1
	for di in d:
		dil = len(d[di])
		for dj in range(dil // 2):
			(si, ei) = (d[di][dj], d[di][dil - dj - 1])
			mc = 0
			for j in range(201):
				mc = max(mc, cnt[j][ei - 1] - cnt[j][si])
			ans = max(ans, 2 * (dj + 1) + mc)
	for di in d:
		ans = max(ans, len(d[di]))
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
ans = []
for _ in range(t):
	n = int(input())
	(*a,) = map(int, input().split())
	if n == 1:
		ans.append(1)
		continue
	cnt = [[x == i for x in a] for i in range(1, 27)]
	for i in range(n - 1):
		for j in range(26):
			cnt[j][i + 1] += cnt[j][i]
	ret = 0
	for i in range(n):
		for j in range(i, n):
			tmp1 = tmp2 = 0
			for x in range(26):
				tmp1 = max(tmp1, min(cnt[x][i], cnt[x][-1] - cnt[x][j]))
				tmp2 = max(tmp2, cnt[x][j] - cnt[x][i])
			ret = max(ret, tmp1 * 2 + tmp2)
	ans.append(ret)
print('\n'.join(map(str, ans)))


for _ in range(int(input())):
	n = int(input())
	r = list(map(int, input().split()))
	d = {i: [] for i in range(1, 27)}
	for i in range(n):
		d[r[i]].append(i)
	ans = 1
	for end in range(1, 27):
		c = 1
		while c * 2 <= len(d[end]):
			(ll, rr) = (d[end][c - 1] + 1, d[end][-c] - 1)
			dd = [0] * 27
			for p in range(ll, rr + 1):
				dd[r[p]] += 1
			ans = max(ans, max(dd) + 2 * c)
			c += 1
	print(ans)


def find_leftmost_right(a, k):
	return indices[a][-k]

def most_repeats(j1, j2):
	if j2 >= j1:
		return max((repeats[j0][j2] - repeats[j0][j1 - 1] for j0 in range(200)))
	return 0
T = int(input())
for t in range(T):
	N = int(input())
	A = list(map(int, input().split()))
	repeats = [[0] * N for _ in range(200)]
	indices = [[] for _ in range(200)]
	for i in range(0, N):
		if i > 0:
			for j in range(200):
				repeats[j][i] = repeats[j][i - 1]
		repeats[A[i] - 1][i] += 1
		indices[A[i]].append(i)
	result = 1
	for i1 in range(len(A)):
		c = repeats[A[i1] - 1][i1]
		i2 = find_leftmost_right(A[i1], c)
		if i2 > i1:
			result = max(result, 2 * c + most_repeats(i1 + 1, i2 - 1))
	print(result)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	c = [[0 for i in range(n)]]
	for i in range(1, 27):
		k = []
		if a[0] == i:
			k.append(1)
			count = 1
		else:
			k.append(0)
			count = 0
		for j in range(1, n):
			if a[j] == i:
				count += 1
			k.append(count)
		c.append(k[:])
	maxx = 0
	for i in range(1, 27):
		maxxi = 0
		for j in range(1, 27):
			count = c[j][n - 1]
			if count == 0 or c[i][n - 1] == 0:
				continue
			else:
				for pi in range(0, n):
					if a[pi] == i:
						break
				for pj in range(n - 1, -1, -1):
					if a[pj] == i:
						break
				nu = 2
				while pj - pi > 1:
					count = max(count, nu + c[j][pj - 1] - c[j][pi])
					for o in range(pi + 1, pj):
						if a[o] == i:
							break
					pi = o
					for o in range(pj - 1, pi, -1):
						if a[o] == i:
							break
					pj = o
					nu += 2
			maxxi = max(maxxi, count)
		maxx = max(maxx, maxxi)
	print(maxx)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(lambda x: int(x) - 1, input().split()))
	nxt = [[-1] * 26 for _ in range(n)]
	prv = [[-1] * 26 for _ in range(n)]
	fst = [-1] * 26
	lst = [-1] * 26
	initc = [0] * 26
	for i in range(n):
		initc[arr[i]] += 1
		if fst[arr[i]] == -1:
			fst[arr[i]] = i
		else:
			for j in range(i - 1, -1, -1):
				if arr[j] == arr[i]:
					prv[i][arr[i]] = j
					nxt[j][arr[i]] = i
					break
	for i in range(n - 1, -1, -1):
		if lst[arr[i]] == -1:
			lst[arr[i]] = i
	ans = 0
	for i in range(26):
		cnt = initc[:]
		ans = max(cnt[i], ans)
		cnt[i] = 0
		if fst[i] == -1:
			continue
		l = fst[i]
		r = lst[i]
		if l == r:
			ans = max(1, ans)
			continue
		real_l = 0
		real_r = n - 1
		prsf = 2
		ans = max(ans, max(cnt))
		while l < r:
			while l > real_l:
				cnt[arr[real_l]] -= 1
				real_l += 1
			while r < real_r:
				cnt[arr[real_r]] -= 1
				real_r -= 1
			ans = max(ans, max(cnt) + prsf)
			l = nxt[l][i]
			r = prv[r][i]
			prsf += 2
	print(ans)


import sys
from itertools import accumulate

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
for _ in range(INT()):
	N = INT()
	A = [0] + [a - 1 for a in LIST()]
	acc = list2d(26, N + 1, 0)
	for (i, a) in enumerate(A[1:], 1):
		acc[a][i] = 1
	for a in range(26):
		acc[a] = list(accumulate(acc[a]))
	ans = 0
	for i in range(N + 1):
		for j in range(i, N + 1):
			y = 0
			for a in range(26):
				y = max(y, acc[a][j] - acc[a][i])
			x = 0
			for a in range(26):
				x = max(x, min(acc[a][i], acc[a][N] - acc[a][j]))
			ans = max(ans, x * 2 + y)
	print(ans)


t = int(input())
maxa = 27
for _ in range(t):
	n = int(input())
	ar = [int(x) for x in input().split()]
	tbc = []
	maxleng = 0
	leng = 1
	ftot = [[0 for j in range(n)] for i in range(maxa + 1)]
	btot = [[0 for j in range(n)] for i in range(maxa + 1)]
	for i in range(n):
		for j in range(1, maxa + 1):
			ftot[j][i] = ftot[j][i - 1]
			if ar[i] == j:
				ftot[j][i] += 1
	arrev = ar[::-1]
	for i in range(n):
		for j in range(1, maxa + 1):
			btot[j][i] = btot[j][i - 1]
			if arrev[i] == j:
				btot[j][i] += 1
	for i in range(len(btot)):
		btot[i] = btot[i][::-1]
	for i in range(n):
		for j in range(i, n):
			if ar[i] == ar[j]:
				val = ar[i]
				leng = 1 + ftot[val][j] - ftot[val][i]
				maxext = 0
				for k in range(1, maxa + 1):
					if k != val:
						ext = 2 * min(ftot[k][i], btot[k][j])
						if ext > maxext:
							maxext = ext
				leng += maxext
				if leng > maxleng:
					maxleng = leng
	print(maxleng)


import sys
sys.setrecursionlimit(50000)
input = sys.stdin.readline

def input_list():
	return map(int, input().split())

def r(n_i, n_j, i, j, m=[]):
	n = n_i + n_j
	if n_i == 0:
		return n_j
	elif n_j == 0:
		return n_i
	elif m[0] == m[n - 1] and m[0] == i:
		return 2 + r(n_i - 2, n_j, i, j, m[1:n - 1])
	elif m[0] == j:
		return max(n_j, r(n_i, n_j - 1, i, j, m[1:n]))
	else:
		return max(n_j, r(n_i, n_j - 1, i, j, m[0:n - 1]))

def f():
	n = int(input())
	l = list(input_list())
	f_result = 0
	s = set(l)
	for i in s:
		for j in s:
			m = []
			n_i = 0
			n_j = 0
			for k in l:
				if k == i:
					m.append(k)
					n_i += 1
				elif k == j:
					m.append(k)
					n_j += 1
			f_result = max(f_result, r(n_i, n_j, i, j, m))
	print(f_result)

def main():
	t = int(input())
	for _ in range(t):
		f()
main()


import sys

class E2ThreeBlocksPalindromeHardVersion:

	def solve(self):
		for _ in range(int(input())):
			n = int(input())
			arr = [int(_) for _ in input().split()]
			pos = {x: [] for x in arr}
			for (i, x) in enumerate(arr):
				pos[x].append(i)
			ans = 1
			for a in pos:
				ln = len(pos[a])
				for _x in range(ln // 2):
					x = _x + 1
					(l, r) = (pos[a][_x] + 1, pos[a][ln - _x - 1] - 1)
					cnt = {item: 0 for item in arr[l:r + 1]}
					for v in arr[l:r + 1]:
						cnt[v] += 1
					most_common = max(cnt.values()) if cnt.values() else 0
					ans = max(ans, 2 * x + most_common)
			print(ans)
solver = E2ThreeBlocksPalindromeHardVersion()
input = sys.stdin.readline
solver.solve()


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	p = dict()
	mx = 0
	for i in range(n):
		if a[i] not in p.keys():
			p[a[i]] = list()
		p[a[i]].append(i)
		mx = max(mx, len(p[a[i]]))
	for x in range(1, n // 2 + 1):
		for e in p.keys():
			if len(p[e]) < 2 * x:
				continue
			l = p[e][x - 1]
			r = p[e][len(p[e]) - x]
			for e2 in p.keys():
				if e2 == e:
					continue
				count = 0
				for i in p[e2]:
					if i >= r:
						break
					if i > l:
						count += 1
				mx = max(mx, count + 2 * x)
	print(mx)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = {i: [] for i in range(1, 27)}
	i = 0
	for x in a:
		d[x].append(i)
		i += 1
	ans = 1
	for x in d:
		b = d[x]
		l = len(b)
		for i in range(0, l // 2):
			(x, y) = (b[i] + 1, b[-i - 1])
			f = [0] * 27
			for j in range(x, y):
				f[a[j]] += 1
			ans = max(ans, max(f) + 2 * (i + 1))
	print(ans)


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from sys import stdout
for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().strip().split()))
	b = {}
	c = {}
	mal = 0
	for i in range(n):
		if b.get(a[i]) == None:
			b[a[i]] = [i]
			c[a[i]] = []
		else:
			b[a[i]].append(i)
	for i in c:
		for j in range(n):
			if j != 0:
				c[i].append(c[i][-1] + (a[j] == int(i)))
			else:
				c[i].append(int(a[j] == int(i)))
		mal = max(mal, c[i][-1])
	if mal != n:
		for k in b:
			i = 0
			j = len(b[k]) - 1
			l = b[k][i]
			r = b[k][j]
			while l < r and i < j:
				ma = 0
				for m in b:
					if m != k:
						x = c[int(m)][l]
						y = c[int(m)][r]
						ma = max(ma, y - x)
				mal = max(2 * (i + 1) + ma, mal)
				i = i + 1
				j = j - 1
				l = b[k][i]
				r = b[k][j]
	stdout.write(str(mal) + '\n')


I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	(n,) = I()
	count = [[0] * 201 for i in range(n)]
	a = I()
	for i in range(n):
		for j in range(1, 201):
			count[i][j] = count[i - 1][j]
		count[i][a[i]] += 1
	ans = 1
	for i in range(1, 201):
		s = 0
		e = n - 1
		an = 0
		while s < e:
			while s < n and a[s] != i:
				s += 1
			while e >= 0 and a[e] != i:
				e -= 1
			if s < e:
				an += 2
				temp = [0] * 201
				for j in range(201):
					temp[j] = count[e - 1][j] - count[s][j]
				ans = max(ans, an + max(temp))
			s += 1
			e -= 1
	print(ans)


def getmid(s, e, count):
	mx = -1
	for i in range(201):
		mx = max(count[e][i] - count[s][i], mx)
	return mx
for tc in range(int(input())):
	n = int(input())
	a = list(map(int, input().split(' ')))
	count = n * [201 * [0]]
	pos = [[] for i in range(201)]
	for i in range(n):
		count[i] = count[i - 1].copy()
		count[i][a[i]] += 1
		pos[a[i]].append(i)
	ans = 0
	for i in range(len(a)):
		l = count[i][a[i]]
		j = pos[a[i]][-l]
		if i < j:
			ans = max(ans, 2 * l + getmid(i, j - 1, count))
		elif i == j:
			ans = max(ans, 2 * l - 1)
	print(ans)


def match(a, x, s, e):
	matches = []
	while s <= e:
		while s <= e and a[s] != x:
			s += 1
		while s <= e and a[e] != x:
			e -= 1
		if s <= e:
			matches.append((s, e))
			s += 1
			e -= 1
	return matches

def solve(a):
	ps = [[0] * 27]
	for x in a:
		p = ps[-1][:]
		p[x] += 1
		ps.append(p)
	sol = 1
	for first in range(1, 27):
		matches = match(a, first, 0, len(a) - 1)
		for (i, (s, e)) in enumerate(matches):
			if s != e:
				sol = max(sol, 2)
			for second in range(1, 27):
				total2 = ps[e][second] - ps[s + 1][second]
				if total2 > 0:
					sol = max(sol, (i + 1) * 2 + total2)
	return sol
t = int(input())
for _ in range(t):
	input()
	a = list(map(int, input().split()))
	print(solve(a))


from collections import deque

def solve2_d(a):
	d1 = deque((i for i in range(len(a)) if a[i] == 1))
	d2 = deque((i for i in range(len(a)) if a[i] == 2))
	d1_left = []
	d1_right = []
	best = len(d2)
	while len(d1) >= 2:
		d1_left.append(d1.popleft())
		d1_right.append(d1.pop())
		while len(d2) > 0 and d2[0] < d1_left[-1]:
			d2.popleft()
		while len(d2) > 0 and d2[-1] > d1_right[-1]:
			d2.pop()
		best = max(best, len(d1_left) + len(d1_right) + len(d2))
	return best
t = int(input())
for i in range(t):
	n = int(input())
	a = [int(v) for v in input().split()]
	best = -1
	for x in range(1, 26 + 1):
		for y in range(1, 26 + 1):
			a2 = [v for v in a if v == x or v == y]
			a2 = [1 if v == x else 2 for v in a2]
			best = max(best, sum((1 for v in a2 if v == 1)))
			best = max(best, sum((1 for v in a2 if v == 2)))
			if x != y:
				best = max(best, solve2_d(a2))
	print(best)


t = int(input())
for _ in range(t):
	n = int(input())
	D = {}
	DC = {}
	DS = {}
	A = list(map(int, input().split()))
	for i in range(n):
		if A[i] in D:
			D[A[i]].append(i)
			DS[A[i]][i] = 1
			DC[A[i]] += 1
		else:
			D[A[i]] = [i]
			DS[A[i]] = [0 for __ in range(n)]
			DS[A[i]][i] = 1
			DC[A[i]] = 1
	for i in DS:
		for k in range(n - 1):
			DS[i][k + 1] += DS[i][k]
	M = max((DC[i] for i in DC))
	for i in D:
		m = DC[i]
		for j in D:
			if i != j:
				for k in range(1, m // 2 + 1):
					(l, r) = (D[i][k - 1], D[i][-k])
					if l != 0:
						cnt = DS[j][r - 1] - DS[j][l - 1]
					else:
						cnt = DS[j][r - 1]
					if M < cnt + k * 2:
						M = cnt + k * 2
	print(M)


t = int(input())
a = list()
dp = list()

def getInd(j, i):
	global n, a, dp
	for k in range(n - 1, i, -1):
		bias = 0
		if a[k] == j + 1:
			bias = 1
		if dp[j][n - 1] - dp[j][k] + bias == dp[j][i]:
			return k
	return -1

def getMax(j, i, ind):
	global dp
	if ind - i == 1:
		return 0
	m = 0
	for it in range(26):
		m = max(m, dp[it][ind - 1] - dp[it][i])
	return m
for _ in range(t):
	dp = []
	n = int(input())
	for i in range(26):
		dp.append([0 for j in range(n)])
	a = list(map(int, input().split()))
	for i in range(n):
		for j in range(1, 27):
			if j == a[i]:
				dp[j - 1][i] = dp[j - 1][i - 1] + 1
			else:
				dp[j - 1][i] = dp[j - 1][i - 1]
	ans = 1
	for i in range(n - 1):
		for j in range(26):
			if dp[j][i] <= 0 or dp[j][i] == dp[j][i - 1]:
				continue
			ind = getInd(j, i)
			if ind != -1:
				m = getMax(j, i, ind)
				ans = max(ans, 2 * dp[j][i] + m)
	print(ans)


from sys import stdin
AI = 200
N = 2000
occ = [[0 for i in range(N + 1)] for ai in range(AI)]
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	a = [0, *(int(x) - 1 for x in input().split())]
	for ai in range(AI):
		occ[ai][0] = 0
		for i in range(1, n + 1):
			occ[ai][i] = occ[ai][i - 1] + (a[i] == ai)
	s = [[0, *(i for i in range(1, n + 1) if a[i] == ai)] for ai in range(AI)]
	t = [[n, *(i - 1 for i in range(n, 0, -1) if a[i] == ai)] for ai in range(AI)]
	ans = 0
	for ai in range(AI):
		for x in range(occ[ai][n] // 2 + 1):
			for bi in range(AI):
				ans = max(ans, 2 * x + occ[bi][t[ai][x]] - occ[bi][s[ai][x]])
	print(ans)


from collections import deque, defaultdict, Counter
from bisect import bisect_left, bisect
import math

def solve(inf):
	n = inf[0]
	a = list(map(int, input().split()))
	uni = list(set(a))
	if len(uni) == 1:
		return n
	ans = 0
	count = defaultdict(lambda : 0)
	indxs = defaultdict(lambda : [])
	for i in range(len(a)):
		indxs[a[i]].append(i)
	pre = []
	for i in range(len(a)):
		count[a[i]] += 1
		pre.append(count.copy())
	pre.append(defaultdict(lambda : 0))
	for key in indxs:
		l = 0
		r = len(indxs[key]) - 1
		ans = max(ans, r + 1)
		for i in range((r + 1) // 2):
			p = indxs[key][i]
			q = indxs[key][r - i]
			for newkey in indxs:
				if newkey == key:
					continue
				ans = max(ans, pre[q - 1][newkey] - pre[p][newkey] + 2 * (i + 1))
	return ans
for _ in range(int(input())):
	inf = list(map(int, input().split()))
	print(solve(inf))


import sys
input = sys.stdin.buffer.readline
ans = []
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	f = [[0 for _ in range(26)] for _ in range(n)]
	f[0][a[0] - 1] += 1
	for i in range(1, n):
		for j in range(26):
			f[i][j] = f[i - 1][j]
		f[i][a[i] - 1] += 1
	maxLen = 1
	for i in range(-1, n - 1):
		for j in range(i + 1, n):
			tmp = []
			if i == -1:
				tmp = [0] * 26
			else:
				tmp = f[i]
			ar1 = [0] * 26
			maxAr2 = 0
			ar3 = [0] * 26
			for k in range(26):
				ar1[k] = tmp[k]
				maxAr2 = max(maxAr2, f[j][k] - tmp[k])
				ar3[k] = f[n - 1][k] - f[j][k]
			lenij = 0
			for k in range(26):
				lenij = max(lenij, min(ar1[k], ar3[k]))
			lenij *= 2
			lenij += maxAr2
			maxLen = max(maxLen, lenij)
	ans.append(maxLen)
print('\n'.join(map(str, ans)))


import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)

def in_int():
	return int(input())

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

def in_str():
	s = input()
	return list(s[:len(s) - 1])

def in_ints():
	return map(int, input().split())
t = in_int()
for tt in range(t):
	n = in_int()
	nums = in_list()
	count = []
	tmp = [0] * 27
	a = [[] for i in range(27)]
	i = 0
	for xx in nums:
		tmp[xx] += 1
		count.append(list(tmp))
		a[xx].append(i)
		i += 1

	def rc(i, j, c):
		if i > j:
			return 0
		if i == 0:
			return count[j][c]
		else:
			return count[j][c] - count[i - 1][c]

	def mc(i, j):
		if i == 0:
			mx = 0
			for xx in range(1, 27):
				mx = max(mx, count[j][xx])
			return mx
		else:
			mx = 0
			for c in range(1, 27):
				mx = max(mx, count[j][c] - count[i - 1][c])
			return mx
	ans = mc(0, n - 1)
	for aa in a:
		i = 0
		j = len(aa) - 1
		while i < j:
			ans = max(ans, 2 * (i + 1) + mc(aa[i] + 1, aa[j] - 1))
			i += 1
			j -= 1
	print(ans)


from sys import stdin, stdout
from math import gcd, sqrt, factorial, pi, inf
from collections import deque, defaultdict
from bisect import bisect, bisect_left
from time import time
from itertools import permutations as per
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\r\n')
L = lambda : list(R())
P = lambda x: stdout.write(str(x) + '\n')
lcm = lambda x, y: x * y // gcd(x, y)
nCr = lambda x, y: f[x] * inv(f[y] * f[x - y] % N) % N
inv = lambda x: pow(x, N - 2, N)
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7

def get_ans(x, y):
	global ans
	s = sorted(v[x] + v[y])
	p = [0] * ln[x]
	q = [0] * ln[y]
	i = 0
	j = 0
	cntx = 0
	cnty = 0
	for k in range(ln[x] + ln[y]):
		if a[s[k]] == x:
			p[i] = cnty
			i += 1
			cntx += 1
		else:
			q[j] = cntx
			j += 1
			cnty += 1
	i = 0
	j = 0
	cntx = 0
	cnty = 0
	for k in range(ln[x] + ln[y]):
		if i >= ln[x] // 2 and j >= ln[y] // 2:
			break
		if i < ln[x] // 2 and a[s[-k - 1]] == x:
			ans = max(ans, (i + 1) * 2 + ln[y] - cnty - p[i])
			i += 1
		elif j < ln[y] // 2 and a[s[-k - 1]] == y:
			ans = max(ans, (j + 1) * 2 + ln[x] - cntx - q[j])
			j += 1
		if a[s[-k - 1]] == x:
			cntx += 1
		else:
			cnty += 1
for _ in range(I()):
	n = I()
	a = L()
	g = len(set(a))
	v = [[] for i in range(201)]
	ln = [0] * 201
	ans = 0
	for i in range(n):
		v[a[i]] += (i,)
		ln[a[i]] += 1
		ans = max(ans, ln[a[i]])
	p = list(set(a))
	z = len(p)
	for i in range(z - 1):
		for j in range(i + 1, z):
			get_ans(p[i], p[j])
	print(ans)


import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
from functools import lru_cache
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
if os.path.exists('out.txt'):
	sys.stdout = open('out.txt', 'w')

def input():
	return sys.stdin.readline()

def mapi(arg=0):
	return map(int if arg == 0 else str, input().split())
for _ in range(int(input())):
	n = int(input())
	a = list(mapi())
	freq = defaultdict(list)
	cur = [0] * 200
	B = [list(cur)]
	for i in range(n):
		cur[a[i]] += 1
		B.append(list(cur))
		freq[a[i]].append(i)
	ans = max((len(i) for i in freq.values()))
	for i in range(200):
		tmp = freq[i]
		for j in range(len(tmp) // 2):
			D1 = B[tmp[j] + 1]
			D2 = B[tmp[~j]]
			for k in range(200):
				ans = max(ans, 2 * (j + 1) + D2[k] - D1[k])
	print(ans)


import sys
import os
from io import BytesIO, IOBase

def cel(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

def mi():
	return map(int, input().split())

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

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def prr(a, sep=' '):
	print(sep.join(map(str, a)))

def dd():
	return defaultdict(int)

def ddl():
	return defaultdict(list)

def ddd():
	return defaultdict(defaultdict(int))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict
from bisect import bisect_left as bl

def num(tmp, i, j):
	l = bl(tmp, i)
	r = bl(tmp, j)
	return r - l
for _ in range(ii()):
	n = ii()
	a = li()
	d = ddl()
	mx = 1
	for i in range(n):
		d[a[i]].append(i)
	for i in d:
		tmp = d[i]
		mx = max(mx, len(tmp))
		for j in range(len(tmp) // 2):
			for k in d:
				if k != i:
					tmpn = num(d[k], tmp[j], tmp[len(tmp) - 1 - j])
					mx = max(2 * (j + 1) + tmpn, mx)
	print(mx)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = int(input())
from bisect import bisect
from collections import defaultdict
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	d = defaultdict(list)
	for j in range(n):
		d[l[j]].append(j)
	ans = 0
	for j in d:
		ans = max(ans, len(d[j]))
		for p in d:
			if p != j:
				for k in range(len(d[j]) // 2):
					x = bisect(d[p], d[j][k])
					y = bisect(d[p], d[j][len(d[j]) - 1 - k])
					if y == x:
						break
					ans = max(ans, y - x + 2 * (k + 1))
	print(ans)


from collections import defaultdict, deque
from itertools import permutations, product, combinations
from functools import lru_cache
from time import time
import sys
from operator import itemgetter
start = time()

def show_time():
	print(time() - start, file=sys.stderr)
try:
	f = open('test.in')

	def ints():
		return map(int, f.readline().strip().split())

	def one_int():
		return int(f.readline())

	def one_string():
		return f.readline().strip()

	def strings():
		return f.readline().strip().split()
except FileNotFoundError:

	def ints():
		return map(int, input().strip().split())

	def one_int():
		return int(input())

	def one_string():
		return input().strip()

	def strings():
		return input().strip().split()

def debug(s):
	print(s, file=sys.stderr)
sys.stderr.write('\n')
from collections import Counter

def ans(numbers, rev_numbers, a, c):
	r = max(c.values())
	for i in range(0, 1 + c[a] // 2):
		(ia, rev_ia) = set_indices(a, i, numbers, rev_numbers)
		if (ia, rev_ia) == (-1, -1):
			continue
		if rev_ia == 0:
			sub_list = numbers[ia:]
		else:
			sub_list = numbers[ia:-rev_ia]
		if sub_list:
			sub_counter = Counter(sub_list)
			r = max(r, 2 * i + max(sub_counter.values()))
		else:
			r = max(r, 2 * i)
	return r

@lru_cache(maxsize=None)
def set_indices(a, i, numbers, rev_numbers):
	if i == 0:
		return (0, 0)
	(ia, rev_ia) = set_indices(a, i - 1, numbers, rev_numbers)
	try:
		ia += numbers[ia:].index(a)
		ia += 1
		rev_ia += rev_numbers[rev_ia:].index(a)
		rev_ia += 1
	except ValueError:
		(ia, rev_ia) = (-1, -1)
	if ia + rev_ia > len(numbers):
		(ia, rev_ia) = (-1, -1)
	return (ia, rev_ia)
t = one_int()
for _ in range(t):
	n = one_int()
	numbers = tuple(list(ints()))
	rev_numbers = numbers[::-1]
	c = Counter(numbers)
	r = max(c.values())
	for a in set(numbers):
		r = max(r, ans(numbers, rev_numbers, a, c))
	print(r)