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 10^4$) — 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 2 \cdot 10^5$) — 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 200$), where $a_i$ is the $i$-th element of $a$. Note that the maximum value of $a_i$ can be up to $200$.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).


-----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: EASY


Solutions:
from sys import stdin, stdout
from math import *
from heapq import *
from collections import *
res = 0

def bestmatch(a, b):
	global res
	if len(a) + len(b) < res:
		return 0
	subres = len(a)
	lid = 0
	rid = len(a) - 1
	x = 0
	y = len(b) - 1
	la = len(a)
	lb = len(b)
	while lid < rid:
		l = a[lid]
		r = a[rid]
		while x < lb:
			if b[x] <= l:
				x += 1
			else:
				break
		while y > 0:
			if r <= b[y]:
				y -= 1
			else:
				break
		if 0 <= x and x <= y and (y < lb):
			if l < b[x] and b[x] <= b[y] and (b[y] < r):
				subres = max(subres, lid + 1 + (y - x + 1) + (la - rid))
		lid += 1
		rid -= 1
	return subres

def main():
	global res
	ntest = int(stdin.readline())
	for test in range(ntest):
		n = int(stdin.readline())
		a = [int(x) for x in stdin.readline().split()]
		poslist = {}
		for (index, x) in enumerate(a, 1):
			if x not in poslist:
				poslist[x] = []
			poslist[x].append(index)
		res = 0
		all_lists = list(poslist.values())
		all_lists.sort(key=lambda lst: len(lst), reverse=True)
		for id1 in range(len(all_lists)):
			for id2 in range(len(all_lists)):
				res = max(res, bestmatch(all_lists[id1], all_lists[id2]))
		stdout.write('%d\n' % res)
	return 0
main()


t = int(input())
u = 0
while u < t:
	n = int(input())
	a = list(map(int, input().split()))
	rama = [[0] * n for i in range(201)]
	sita = [[] for i in range(201)]
	for i in range(n):
		if i > 0:
			s = a[i]
			for j in range(201):
				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(201):
				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


import sys
import copy
input = sys.stdin.readline

def main():
	t = int(input())
	for _ in range(t):
		N = int(input())
		A = [int(x) for x in input().split()]
		ruiseki = [[0] * 201 for j in range(N)]
		for (i, v) in enumerate(A):
			ruiseki[i][v] += 1
			if i != 0:
				for j in range(1, 201):
					ruiseki[i][j] += ruiseki[i - 1][j]
		ans = 1
		for i in range(1, 201):
			l = 0
			r = N - 1
			tmp = 0
			while True:
				while l < N and A[l] != i:
					l += 1
				while r >= 0 and A[r] != i:
					r -= 1
				if l >= r:
					break
				tmp += 2
				ma = 0
				for j in range(1, 201):
					ma = max(ma, ruiseki[r - 1][j] - ruiseki[l][j])
				ans = max(ans, tmp + ma)
				l += 1
				r -= 1
		print(ans)
main()


import sys
input = sys.stdin.buffer.readline

def main():
	ans = []
	m = 200
	for _ in range(int(input())):
		n = int(input())
		(*a,) = map(int, input().split())
		where = [[] for _ in range(m)]
		acc = [[0] * (n + 1) for _ in range(m)]
		for (i, x) in enumerate(a):
			where[x - 1].append(i)
			for j in range(m):
				acc[j][i + 1] = acc[j][i] + (x - 1 == j)
		ret = 0
		for (q, l) in enumerate(acc):
			ret = max(ret, l[-1])
			if l[-1] == 0:
				continue
			for p in range(m):
				lim = acc[p][-1]
				for r in range(lim // 2):
					fw = where[p][r]
					bw = where[p][~r]
					if ret < 2 * (r + 1) + l[bw] - l[fw + 1]:
						ret = 2 * (r + 1) + l[bw] - l[fw + 1]
		ans.append(ret)
	print('\n'.join(map(str, ans)))
main()


numbers = 200
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)]
	pos = [[] 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
				pos[i].append(j)
			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(max_val):
			bmin = pos[i][x]
			bmax = pos[i][-x - 1]
			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 + 1))
	print(ans)


def max_tbp(xs, a, b, O, C):
	m = 1
	occs = O[a]
	b_cnts = C[b]
	for i in range(len(occs) // 2):
		st = occs[i]
		en = occs[len(occs) - 1 - i]
		cnt = b_cnts[en - 1] - b_cnts[st]
		m = max(m, (i + 1) * 2 + cnt)
	return m
t = int(input())
for _ in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	m = 0
	sA = set(A)
	occs = {}
	cnts = {}
	for a in sA:
		a_occs = []
		a_cnts = []
		cur = 0
		for (i, x) in enumerate(A):
			if x == a:
				cur += 1
				a_occs.append(i)
			a_cnts.append(cur)
		occs[a] = a_occs
		cnts[a] = a_cnts
	for a in sA:
		for b in sA:
			m = max(m, max_tbp(A, a, b, occs, cnts))
	print(m)


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()


from collections import Counter
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	counters = [[] for _ in range(len(arr))]
	counter = [0 for _ in range(201)]
	mp = dict()
	for idx in range(len(arr)):
		counter[arr[idx]] += 1
		counters[idx] = counter.copy()
		mp[arr[idx], counter[arr[idx]]] = idx
	ans = 1
	for idx_v in range(len(arr)):
		v = arr[idx_v]
		occ_v = counters[idx_v][v]
		total_occs_v = counters[-1][v]
		symmetric_idx_v = mp[v, total_occs_v - occ_v + 1]
		if idx_v >= symmetric_idx_v:
			continue
		mx = max([second - first for (first, second) in zip(counters[idx_v], counters[symmetric_idx_v - 1])]) + occ_v * 2
		ans = max(ans, mx)
	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
for _ in range(ii()):
	n = ii()
	a = [0] + li()
	cnt = [[0 for i in range(201)] for j in range(n + 1)]
	ans = 1
	for i in range(1, n + 1):
		for j in range(1, 201):
			cnt[i][j] = cnt[i - 1][j]
		cnt[i][a[i]] += 1
	for i in range(1, 201):
		(la, ra) = (1, n)
		score = 0
		while la < ra:
			while la <= n and a[la] != i:
				la += 1
			while ra >= 1 and a[ra] != i:
				ra -= 1
			if la < ra:
				score += 2
			if score == 0:
				break
			for j in range(1, 201):
				ans = max(ans, score + cnt[ra - 1][j] - cnt[la][j])
			la += 1
			ra -= 1
	print(ans)


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()
	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(1, 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(1, 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(1, 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 sm(c, l, r):
	return occur[c][r + 1] - occur[c][l]
t = int(input())
for z in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	brr = list(set(arr))
	pos = [[] for i in range(201)]
	occur = [[] for i in range(201)]
	for num in brr:
		occur[num].append(0)
		count = 0
		for i in range(n):
			if arr[i] == num:
				pos[num].append(i)
				count = count + 1
			occur[num].append(count)
	ans = 0
	for num in brr:
		ans = max(ans, occur[num][n])
		ln = len(pos[num])
		for k in range(ln // 2):
			l = pos[num][k] + 1
			r = pos[num][ln - k - 1] - 1
			cntin = 0
			for nm in brr:
				cntin = max(cntin, sm(nm, l, r))
			ans = max(ans, 2 * (k + 1) + cntin)
	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(201, len(a) + 1, 0)
	for i in range(len(a)):
		for j in range(1, 201):
			count[j][i + 1] = count[j][i]
		count[a[i]][i + 1] += 1
	dic = {}
	for i in range(len(a)):
		if a[i] in dic:
			dic[a[i]].append(i)
		else:
			dic[a[i]] = [i]
	ans = -1
	for i in dic:
		lis = dic[i]
		l = 0
		r = len(lis) - 1
		tans = 1
		while l < r:
			left = lis[l]
			right = lis[r]
			tmax = 0
			for j in range(1, 201):
				cnt = count[j][right] - count[j][left + 1]
				tmax = max(tmax, cnt)
			tans = max(tans, (l + 1) * 2 + tmax)
			l += 1
			r -= 1
		ans = max(ans, tans)
	for i in range(1, 201):
		ans = max(ans, count[i][n])
	print(ans)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for tests in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	COUNT = [[0] * 201 for i in range(n)]
	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):
		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] * 201
				for j in range(201):
					C[j] = COUNT[eind - 1][j] - COUNT[bind][j]
				ANS = max(ANS, score + max(C))
				bind += 1
				eind -= 1
	print(ANS)


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

def main():
	for _ in range(int(input())):
		n = int(input())
		arr = list(map(int, input().split()))
		x = set(arr)
		c = [[0] * n for _ in range(200)]
		for (i, val) in enumerate(arr):
			for xx in range(200):
				c[xx][i] += c[xx][i - 1]
			c[val - 1][i] += 1
		ans = max(c, key=lambda y: y[-1])[-1]
		for a in x:
			(l, r) = (0, n - 1)
			for cou in range(c[a - 1][-1] // 2 + 1):
				maxi = 0
				while cou and c[a - 1][l - 1] != cou:
					l += 1
				while c[a - 1][r] != c[a - 1][-1] - cou:
					r -= 1
				for i in x:
					if i == a:
						continue
					maxi = max(maxi, c[i - 1][r] - (0 if l == 0 else c[i - 1][l - 1]))
				ans = max(ans, maxi + 2 * cou)
		print(ans)
main()


def solve():
	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 main():
	t = int(input())
	for _ in range(t):
		solve()
main()


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] * 201 for _ in range(n + 1)]
	st = [[] for _ in range(201)]
	for i in range(1, n + 1):
		st[a[i - 1]].append(i)
		for j in range(1, 201):
			pre[i][j] = pre[i - 1][j]
		pre[i][a[i - 1]] += 1
	ans = 0
	for i in range(1, 201):
		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, 201):
				if i == k:
					continue
				mid = max(mid, pre[idx2][k] - pre[idx1][k])
			ans = max(ans, 2 * (j + 1) + mid)
	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(201)]
	fl = [{} for i in range(201)]
	count = [0 for i in range(201)]
	cal = [[0 for i in range(201)] for i in range(n + 1)]
	for i in range(n):
		for j in range(1, 201):
			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(201)]
	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, 201):
		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, 201):
				if r - 1 < l:
					continue
				g = cal[r - 1][k] - cal[l][k]
				maxi = max(maxi, c + g)
	print(maxi)


import io, os
import sys
from functools import lru_cache
from heapq import merge, heapify, heappop, heappush
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as c
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

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

def out(var):
	sys.stdout.write(str(var))

def outln(var):
	sys.stdout.write(str(var) + '\n')

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	n = int(data())
	arr = l()
	dp = [[0 for i in range(201)] for j in range(n)]
	for i in range(n):
		for j in range(1, 201):
			dp[i][j] = dp[i - 1][j]
		dp[i][arr[i]] += 1
	answer = 1
	for i in set(arr):
		(low, high, cnt) = (0, n - 1, 0)
		while low < high:
			while low < high and arr[low] != i:
				low += 1
			while low < high and arr[high] != i:
				high -= 1
			if low < high:
				cnt += 2
				for j in range(1, 201):
					answer = max(answer, dp[high - 1][j] - dp[low][j] + cnt)
				low += 1
				high -= 1
	outln(answer)


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(201)]
	sm = [[0] * n for _ in range(201)]
	for (i, u) in enumerate(ls):
		p[u].append(i)
	for i in range(1, 201):
		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, 201):
			mx = max(mx, sm[al][to] - sm[al][fm - 1])
		return mx
	mx = max([len(p[i]) for i in range(1, 201)])
	for al in range(1, 201):
		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)


from functools import cmp_to_key
from collections import deque, Counter
from heapq import heappush, heappop
from math import log, ceil
import sys
import os
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')
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def ii():
	return int(inp())

def si():
	return str(inp())

def li(lag=0):
	l = list(map(int, inp().split()))
	if lag != 0:
		for i in range(len(l)):
			l[i] += lag
	return l

def mi(lag=0):
	matrix = list()
	for i in range(n):
		matrix.append(li(lag))
	return matrix

def lsi():
	return list(map(str, inp().split()))

def print_list(lista, space=' '):
	print(space.join(map(str, lista)))

def bisect_left(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] < x:
			left = mid + 1
		else:
			right = mid
	return left

def bisect_right(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] > x:
			right = mid
		else:
			left = mid + 1
	return left

def bisect_elements(a, x):
	return bisect_right(a, x) - bisect_left(a, x)
MOD = 10 ** 9 + 7
maxN = 5
FACT = [0] * maxN
INV_FACT = [0] * maxN

def add(x, y):
	return (x + y) % MOD

def multiply(x, y):
	return x * y % MOD

def power(x, y):
	if y == 0:
		return 1
	elif y % 2:
		return multiply(x, power(x, y - 1))
	else:
		a = power(x, y // 2)
		return multiply(a, a)

def inverse(x):
	return power(x, MOD - 2)

def divide(x, y):
	return multiply(x, inverse(y))

def allFactorials():
	FACT[0] = 1
	for i in range(1, maxN):
		FACT[i] = multiply(i, FACT[i - 1])

def inverseFactorials():
	n = len(INV_FACT)
	INV_FACT[n - 1] = inverse(FACT[n - 1])
	for i in range(n - 2, -1, -1):
		INV_FACT[i] = multiply(INV_FACT[i + 1], i + 1)

def coeffBinom(n, k):
	if n < k:
		return 0
	return multiply(FACT[n], multiply(INV_FACT[k], INV_FACT[n - k]))

def create_graph(n, m, undirected=1, unweighted=1):
	graph = [[] for i in range(n)]
	if unweighted:
		for i in range(m):
			[x, y] = li(lag=-1)
			graph[x].append(y)
			if undirected:
				graph[y].append(x)
	else:
		for i in range(m):
			[x, y, w] = li(lag=-1)
			w += 1
			graph[x].append([y, w])
			if undirected:
				graph[y].append([x, w])
	return graph

def create_tree(n, unweighted=1):
	children = [[] for i in range(n)]
	if unweighted:
		for i in range(n - 1):
			[x, y] = li(lag=-1)
			children[x].append(y)
			children[y].append(x)
	else:
		for i in range(n - 1):
			[x, y, w] = li(lag=-1)
			w += 1
			children[x].append([y, w])
			children[y].append([x, w])
	return children

def dist(tree, n, A, B=-1):
	s = [[A, 0]]
	(massimo, massimo_nodo) = (0, 0)
	distanza = -1
	v = [-1] * n
	while s:
		(el, dis) = s.pop()
		if dis > massimo:
			massimo = dis
			massimo_nodo = el
		if el == B:
			distanza = dis
		for child in tree[el]:
			if v[child] == -1:
				v[child] = 1
				s.append([child, dis + 1])
	return (massimo, massimo_nodo, distanza)

def diameter(tree):
	(_, foglia, _) = dist(tree, n, 0)
	(diam, _, _) = dist(tree, n, foglia)
	return diam

def dfs(graph, n, A):
	v = [-1] * n
	s = [[A, 0]]
	v[A] = 0
	while s:
		(el, dis) = s.pop()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def bfs(graph, n, A):
	v = [-1] * n
	s = deque()
	s.append([A, 0])
	v[A] = 0
	while s:
		(el, dis) = s.popleft()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def parents_children_root_unrooted_tree(tree, n, root=0):
	q = deque()
	visited = [0] * n
	parent = [-1] * n
	children = [[] for i in range(n)]
	q.append(root)
	while q:
		all_done = 1
		visited[q[0]] = 1
		for child in tree[q[0]]:
			if not visited[child]:
				all_done = 0
				q.appendleft(child)
		if all_done:
			for child in tree[q[0]]:
				if parent[child] == -1:
					parent[q[0]] = child
					children[child].append(q[0])
			q.popleft()
	return (parent, children)

def all_longest_path_passing_from_node(parent, children, n):
	q = deque()
	visited = [len(children[i]) for i in range(n)]
	downwards = [[0, 0] for i in range(n)]
	upward = [1] * n
	longest_path = [1] * n
	for i in range(n):
		if not visited[i]:
			q.append(i)
			downwards[i] = [1, 0]
	while q:
		node = q.popleft()
		if parent[node] != -1:
			visited[parent[node]] -= 1
			if not visited[parent[node]]:
				q.append(parent[node])
		else:
			root = node
		for child in children[node]:
			downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse=True)[0:2]
	s = [node]
	while s:
		node = s.pop()
		if parent[node] != -1:
			if downwards[parent[node]][0] == downwards[node][0] + 1:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1])
			else:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0])
		longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1
		for child in children[node]:
			s.append(child)
	return longest_path

def occ(c, letter, L, R):
	return c[letter][R + 1] - c[letter][L]
K = 200
for test in range(ii()):
	n = ii()
	l = li(-1)
	c = [[0 for i in range(n + 1)] for j in range(K)]
	letters = [[] for j in range(K)]
	for j in range(n):
		letters[l[j]].append(j)
	g = 0
	for i in range(K):
		g = max(g, len(letters[i]))
	for j in range(1, n + 1):
		for i in range(K):
			c[i][j] = c[i][j - 1]
		letter = l[j - 1]
		c[letter][j] += 1
	for j in range(n):
		letter = l[j]
		o = occ(c, letter, 0, j)
		index = letters[letter][-o] - 1
		massimo = 0
		if j < index:
			for adj in range(K):
				massimo = max(massimo, occ(c, adj, j + 1, index))
			g = max(g, 2 * o + massimo)
	print(g)


import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__

def go():
	n = int(input())
	a = list(map(int, input().split()))
	d = list(set(a))
	rd = {aa: i for (i, aa) in enumerate(d)}
	a = [rd[aa] for aa in a]
	m = len(d)
	cnt = {}
	cnt_loc = {}
	cum = [0] * m
	cums = []
	for (i, aa) in enumerate(a):
		cnt[aa] = cnt.get(aa, 0) + 1
		cum[aa] += 1
		cnt_loc.setdefault(aa, {})[cnt[aa]] = i
		cums.append(cum.copy())
	best = 1
	for aa in range(m):
		cnt_a = cnt[aa]
		for ca in range(1, cnt_a // 2 + 1):
			left = cnt_loc[aa][ca]
			right = cnt_loc[aa][cnt_a - ca + 1]
			betw = max((rr - ll for (rr, ll) in zip(cums[right - 1], cums[left])))
			best = max(best, 2 * ca + betw)
	return best
t = int(input())
ans = []
for _ in range(t):
	ans.append(str(go()))
print('\n'.join(ans))


for _ in range(int(input())):
	n = int(input())
	a = [int(x) - 1 for x in input().split()]
	id = [[] for i in range(200)]
	cnt = [[0] * n for i in range(200)]
	for (i, x) in enumerate(a):
		cnt[x][i] += 1
		id[x].append(i)
	for i in range(200):
		for j in range(1, n):
			cnt[i][j] += cnt[i][j - 1]
	res = 1
	for a in range(200):
		(l, r, t) = (0, len(id[a]) - 1, 2)
		while l < r:
			for b in range(200):
				res = max(res, t + cnt[b][id[a][r] - 1] - cnt[b][id[a][l]])
			(l, r, t) = (l + 1, r - 1, t + 2)
	print(res)


from collections import defaultdict

def solve():
	N = int(input())
	A = list(map(int, input().split()))
	D = defaultdict(list)
	Dv = defaultdict(int)
	dp = [[0 for i in range(N + 1)] for j in range(201)]
	for (i, x) in enumerate(A):
		Dv[x] += 1
		D[x].append(i + 1)
		dp[x][i + 1] += 1
	for i in range(201):
		for j in range(1, N + 1):
			dp[i][j] += dp[i][j - 1]
	ans = max(Dv.values())
	for value in D.keys():
		S = len(D[value])
		for i in range(1, S // 2 + 1):
			left = D[value][i - 1]
			right = D[value][-i]
			for j in range(201):
				ans = max(ans, i * 2 + dp[j][right - 1] - dp[j][left])
	print(ans)

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


import bisect
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	variety = list(set(arr))
	cnts = [[0] * (n + 1) for _ in range(201)]
	poss = [[] for _ in range(201)]
	for i in range(n):
		cnts[arr[i]][i] += 1
		poss[arr[i]].append(i)
		for j in range(201):
			cnts[j][i] += cnts[j][i - 1]
	ans = 0
	for i in range(201):
		tmp = cnts[i][n - 1]
		ans = max(ans, tmp)
	for a in variety:
		for i in range(n):
			l = poss[a][i]
			r = poss[a][-(i + 1)]
			if l >= r:
				break
			tmp = 0
			for j in range(201):
				if j == a:
					continue
				tmp = max(tmp, cnts[j][r] - cnts[j][l])
			tmp += 2 * (i + 1)
			ans = max(ans, tmp)
	print(ans)


from collections import defaultdict

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	V = max(a)
	ans = 0
	cnt = [[0] * (n + 1) for i in range(V + 1)]
	for (i, v) in enumerate(a):
		cnt[v][i + 1] = 1
	for i in range(1, n + 1):
		for j in range(V + 1):
			cnt[j][i] += cnt[j][i - 1]
	subcnt = [defaultdict(int) for i in range(V + 1)]
	appear_cnt = [0] * (V + 1)
	for (i, v) in enumerate(a):
		subcnt[v][appear_cnt[v] + 1] = i + 1
		appear_cnt[v] += 1
	for x in range(1, V + 1):
		ans = max(ans, cnt[x][n])
		if cnt[x][n] == 0:
			continue
		xcnt = cnt[x][n]
		for c in range(1, xcnt // 2 + 1):
			lx = subcnt[x][c]
			rx = subcnt[x][xcnt - c + 1]
			ans = max(ans, 2 * c + max((cnt[y][rx - 1] - cnt[y][lx] for y in range(V + 1))))
	print(ans)
	return

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


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	cnt = [[0] * 201 for i in range(n)]
	prev = [-1] * n
	pos = [-1] * 201
	ans = 0
	for i in range(n):
		for j in range(201):
			cnt[i][j] = cnt[i - 1][j]
		cnt[i][a[i]] += 1
		prev[i] = pos[a[i]]
		pos[a[i]] = i
		ans = max(ans, cnt[i][a[i]])
	for i in range(n):
		if i >= pos[a[i]]:
			continue
		for j in range(201):
			ans = max(ans, cnt[pos[a[i]] - 1][j] - cnt[i][j] + cnt[i][a[i]] * 2)
		pos[a[i]] = prev[pos[a[i]]]
	print(ans)


t = int(input())
for ti in range(t):
	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)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	dp = [[0] * 201 for i in range(n)]
	for i in range(n):
		for j in range(201):
			dp[i][j] = dp[i - 1][j]
		dp[i][a[i]] += 1
	m = 1
	for i in range(201):
		(l, r, c) = (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:
				c += 2
				for j in range(201):
					m = max(m, c + dp[r - 1][j] - dp[l][j])
				l += 1
				r -= 1
	print(m)


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


import sys
input = sys.stdin.buffer.readline

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


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, c, appears):
	if j < i:
		return 0
	return appears[j][c] - (appears[i - 1][c] if i > 0 else 0)

def solve(n, A):
	pos = [[] for _ in range(201)]
	appears = []
	for (i, a) in enumerate(A):
		pos[a].append(i)
		if i > 0:
			appears.append(appears[i - 1].copy())
		else:
			appears.append([0] * 201)
		appears[i][a] += 1
	sortpos = sorted([(len(x), i, x) for (i, x) in enumerate(pos)], reverse=True)
	ans = 1
	for (xlen, x, posx) in sortpos:
		if xlen <= 0:
			break
		for i in range(len(posx) // 2):
			xnum = (i + 1) * 2
			(left, right) = (posx[i] + 1, posx[len(posx) - i - 1] - 1)
			for (yposes, y, _) in sortpos:
				if xnum + yposes <= ans:
					break
				ynum = subr(left, right, y, appears)
				ans = max(ans, xnum + ynum)
	return ans
t = readint()
for _ in range(t):
	n = readint()
	A = readints()
	print(solve(n, A))


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())
for _ in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	counters = [[] for _ in range(len(arr))]
	counter = [0 for _ in range(201)]
	mp = dict()
	for idx in range(len(arr)):
		counter[arr[idx]] += 1
		counters[idx] = counter.copy()
		mp[arr[idx], counter[arr[idx]]] = idx
	ans = 1
	for idx_v in range(len(arr)):
		v = arr[idx_v]
		occ_v = counters[idx_v][v]
		total_occs_v = counters[-1][v]
		symmetric_idx_v = mp[v, total_occs_v - occ_v + 1]
		if idx_v >= symmetric_idx_v:
			continue
		mx = max([second - first for (first, second) in zip(counters[idx_v], counters[symmetric_idx_v - 1])]) + occ_v * 2
		ans = max(ans, mx)
	print(ans)


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] * 201]
		res = 0
		for i in arr:
			now = sm[-1].copy()
			now[i] += 1
			sm.append(now)
			res = max(now[i], res)
		for i in range(201):
			(b, e, sc) = (0, n - 1, 0)
			while b < e:
				while b < n and arr[b] != i:
					b += 1
				while e > -1 and arr[e] != i:
					e -= 1
				if b >= e:
					continue
				sc += 2
				pre = 0
				for j in range(201):
					pre = max(sm[e][j] - sm[b + 1][j], pre)
				res = max(pre + sc, res)
				b += 1
				e -= 1
		print(res)
main()


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)


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
	indxs = [[] for _ in range(201)]
	pre = [[0 for _ in range(201)] for j in range(n + 1)]
	for i in range(n):
		for j in range(201):
			pre[i][j] = pre[i - 1][j]
		pre[i][a[i]] += 1
		indxs[a[i]].append(i)
	for key in uni:
		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 uni:
				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.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')


alphabet_len = 200
tc = int(input())
while tc > 0:
	n = int(input())
	a = list(map(int, input().split()))
	cnt = [[0] * alphabet_len]
	pos = [[] for _ in range(alphabet_len)]
	for i in range(1, n + 1):
		cnt.append(cnt[i - 1].copy())
		cnt[i][a[i - 1] - 1] += 1
		pos[a[i - 1] - 1].append(i - 1)
	chars = set(filter(lambda c: cnt[n][c] > 0, range(alphabet_len)))
	ans = 0
	for (i, v) in enumerate(pos):
		if not v:
			continue
		ans = max(ans, len(v))
		for p in range(len(v) // 2):
			l = v[p] + 1
			r = v[len(v) - p - 1] - 1
			for c in chars:
				summa = cnt[r + 1][c] - cnt[l][c]
				ans = max(ans, (p + 1) * 2 + summa)
	print(ans)
	tc -= 1


import bisect
for _ in range(int(input())):
	n = int(input())
	a = list(map(lambda x: int(x) - 1, input().split()))
	idx = [[] for _ in range(200)]
	for i in range(len(a)):
		idx[a[i]].append(i)
	mxl = 1
	dp = [[0] * len(a) for _ in range(200)]
	for i in range(len(a)):
		for j in range(200):
			dp[j][i] = dp[j][i - 1]
		dp[a[i]][i] += 1
	for r in range(200):
		mxl = max(mxl, len(idx[r]))
		for c in range(200):
			if c == r:
				continue
			if len(idx[r]) == 0:
				break
			if len(idx[c]) == 0:
				continue
			for i in range(len(idx[r]) // 2):
				k2 = idx[r][-(i + 1)]
				k1 = idx[r][i]
				if k2 <= k1:
					break
				ct = dp[c][k2] - dp[c][k1]
				mxl = max(mxl, 2 * (i + 1) + ct)
	print(mxl)


from collections import defaultdict, deque
from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	mtrx = []
	for _ in range(n):
		mtrx.append([0 for _ in range(201)])
	dct = defaultdict(lambda : deque([]))
	for (i, x) in enumerate(arr):
		mtrx[i][x] += 1
		dct[x].append(i)
	for i in range(1, n):
		for j in range(201):
			mtrx[i][j] += mtrx[i - 1][j]
	msf = 0
	for (k, q) in dct.items():
		occ = 0
		while len(q) > 1:
			l = q.popleft()
			r = q.pop()
			occ += 2
			gb = 0
			if r > l + 1:
				for j in range(201):
					gb = max(gb, mtrx[r - 1][j] - mtrx[l][j])
			msf = max(msf, occ + gb)
		msf = max(msf, occ + len(q))
	print(msf)


from sys import stdin, stdout
input = stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	pre = [[] for i in range(201)]
	for i in range(1, 201):
		s = 0
		for j in a:
			if j == i:
				s += 1
			pre[i].append(s)
	pos = [[] for i in range(201)]
	ans = 0
	for i in range(n):
		pos[a[i]].append(i)
	for i in range(1, 201):
		ans = max(ans, len(pos[i]))
		for j in range(len(pos[i]) // 2):
			count1 = 2 * (j + 1)
			l = pos[i][j] + 1
			r = pos[i][-(j + 1)] - 1
			count2 = 0
			for k in range(1, 201):
				count2 = max(count2, -pre[k][l - 1] + pre[k][r])
			ans = max(ans, count1 + count2)
	print(ans)


import sys
input = sys.stdin.readline
from bisect import bisect_left
Q = int(input())
Query = []
for _ in range(Q):
	N = int(input())
	A = list(map(int, input().split()))
	Query.append((N, A))
for (N, A) in Query:
	dic = {}
	for (i, a) in enumerate(A):
		if a in dic:
			dic[a].append(i)
		else:
			dic[a] = [i]
	Ns = list(dic.keys())
	ans = 0
	for (a, A1) in dic.items():
		ans = max(ans, len(A1))
		for (b, B1) in dic.items():
			if a == b:
				continue
			l1 = 0
			r1 = len(A1) - 1
			l2 = 0
			r2 = len(B1) - 1
			while l1 < r1:
				while l2 <= len(B1) - 1 and B1[l2] < A1[l1]:
					l2 += 1
				while r2 >= 0 and B1[r2] > A1[r1]:
					r2 -= 1
				t = (l1 + 1) * 2 + (r2 - l2 + 1)
				if t > ans:
					ans = t
				l1 += 1
				r1 -= 1
	print(ans)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).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)


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)
	ll = [[0 for i in range(201)] for i in range(n + 1)]
	for i in range(n):
		d[a[i]].append(i)
		for k in range(1, 201):
			ll[i][k] = ll[i - 1][k]
		ll[i][a[i]] += 1
	ans = 1
	for i in d:
		temp = d[i]
		l = len(temp)
		ans = max(ans, l)
		for j in range(l // 2):
			start = temp[j]
			end = temp[l - j - 1]
			for k in d:
				if k != i:
					val = ll[end][k] - ll[start - 1][k]
					ans = max(ans, val + 2 * (j + 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()


import os
import sys
from io import BytesIO, IOBase

def iin():
	return int(input())

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

def main():
	T = iin()
	mx = 200
	while T:
		T -= 1
		n = iin()
		a = lin()
		a1 = [[0] * (mx + 1) for i in range(n)]
		for j in range(n):
			a1[j][a[j]] += 1
		a1 = [[0] * (mx + 1)] + a1
		for i in range(1, n + 1):
			for j in range(mx + 1):
				a1[i][j] += a1[i - 1][j]

		def query(l, r):
			if l >= r:
				return 0
			return max([a1[r - 1][j] - a1[l][j] for j in range(mx + 1)])
		dc = [[] for i in range(mx + 1)]
		for i in range(n):
			dc[a[i]].append(i + 1)
		ans = query(0, n + 1)
		for i in range(mx + 1):
			if dc[i]:
				l1 = len(dc[i])
				(l, r) = (0, len(dc[i]) - 1)
				while l < r:
					x = min(l + 1, l1 - r) * 2 + query(dc[i][l], dc[i][r])
					l += 1
					r -= 1
					ans = max(ans, x)
		print(ans)
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')
main()


from collections import defaultdict
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d1 = [0 for i in range(201)]
	locs = [[] for i in range(201)]
	values = set()
	counts = []
	for i in range(n):
		d1[a[i]] += 1
		counts.append(d1.copy())
		locs[a[i]].append(i)
		values.add(a[i])
	max_len = 1
	for wing in values:
		current_locs = locs[wing]
		for i in range(len(current_locs) // 2):
			left = current_locs[i]
			right = current_locs[-i - 1] - 1
			max_middle = 0
			for key in values:
				middle_len = counts[right][key] - counts[left][key]
				if middle_len > max_middle:
					max_middle = middle_len
			if (i + 1) * 2 + max_middle > max_len:
				max_len = (i + 1) * 2 + max_middle
	print(max_len)


from sys import stdin
input = lambda : stdin.readline().strip()
lin = lambda : list(map(int, input().split()))
iin = lambda : int(input())
main = lambda : map(int, input().split())
from math import ceil, sqrt, factorial, log
from collections import deque
from bisect import bisect_left

def gcd(a, b):
	(a, b) = (max(a, b), min(a, b))
	while a % b != 0:
		(a, b) = (b, a % b)
	return b
mod = 998244353

def solve():
	n = iin()
	l = lin()
	dp = [[0 for i in range(202)] for i in range(n + 2)]
	z = [[] for i in range(202)]
	for i in range(n):
		z[l[i]].append(i)
		for j in range(201):
			dp[i][j] = dp[i - 1][j]
		dp[i][l[i]] += 1
	ans = 0
	for i in range(1, 201):
		t = len(z[i])
		ans = max(ans, t)
		for j in range(ceil(t // 2)):
			x = z[i][j]
			y = z[i][t - j - 1]
			m = 0
			for k in range(1, 201):
				if i != k:
					m = max(m, dp[y][k] - dp[x][k])
			ans = max(ans, 2 * (j + 1) + m)
	print(ans)
qwe = 1
qwe = int(input())
for _ in range(qwe):
	solve()


from sys import stdin, gettrace
if not gettrace():

	def input():
		return next(stdin)[:-1]

def main():

	def solve():
		n = int(input())
		li = [int(x) for x in input().split()]
		counts = [[0] * 201]
		pos = [[] for i in range(201)]
		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(201):
					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)
	q = int(input())
	for _ in range(q):
		solve()
main()


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())
	a = list_input()
	for i in range(n):
		a[i] -= 1
	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)


import sys

def data():
	return sys.stdin.buffer.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
	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) = (0, n - 1)
		cnt = 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:
				cnt += 2
				for j in range(1, 201):
					m = max(m, cnt + dp[end - 1][j] - dp[start][j])
				start += 1
				end -= 1
	out(str(m) + '\n')


def func(a, k):
	maxi = 0
	for i in range(201):
		if i != a:
			maxi = max(maxi, prefix[charocc[a][-k - 1]][i] - prefix[charocc[a][k]][i])
		else:
			maxi = max(maxi, prefix[charocc[a][-k - 1]][i] - prefix[charocc[a][k]][i] - 1)
	return maxi
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	charocc = [[] for i in range(201)]
	prefix = [[0] * 201 for i in range(n)]
	for i in range(n):
		charocc[arr[i]] += [i]
	for i in range(n):
		prefix[i][arr[i]] += 1
	for i in range(1, n):
		for j in range(201):
			prefix[i][j] += prefix[i - 1][j]
	maxim = 0
	for a in range(1, 201):
		for k in range(len(charocc[a]) // 2):
			maxim = max(maxim, 2 * (k + 1) + func(a, k))
	if maxim == 0:
		print(1)
	else:
		print(maxim)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
from itertools import permutations
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())
for ti in range(t):
	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)


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.buffer.readline

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		A = list(map(int, input().split()))
		C = [[0] * (n + 1) for _ in range(200)]
		P = [[] for _ in range(200)]
		for i in range(n):
			for j in range(200):
				if j == A[i] - 1:
					C[j][i + 1] = C[j][i] + 1
					P[j].append(i)
				else:
					C[j][i + 1] = C[j][i]
		ans = 0
		for i in range(200):
			if len(P[i]) >= ans:
				ans = len(P[i])
			if len(P[i]) == 0 or len(P[i]) == 1:
				continue
			for j in range(len(P[i]) // 2 + 1):
				l = P[i][j]
				r = P[i][-(j + 1)]
				if r <= l:
					continue
				for k in range(200):
					temp = 2 * (j + 1) + C[k][r] - C[k][l + 1]
					if temp >= ans:
						ans = temp
		print(ans)
main()


import sys
input = sys.stdin.buffer.readline
MX = 200

def solve(a):
	pref_count = [[0] * (MX + 1)]
	for e in a:
		pref_count.append(pref_count[-1][:])
		pref_count[-1][e] += 1
	indexes = [[] for _ in range(MX + 1)]
	for i in range(len(a)):
		indexes[a[i]].append(i)
	best = max((pref_count[-1][x] for x in range(1, MX + 1)))
	for x in range(1, MX + 1):
		for i in range(len(indexes[x]) // 2):
			l = indexes[x][i]
			r = indexes[x][len(indexes[x]) - 1 - i]
			for y in range(1, MX + 1):
				if x != y:
					best = max(best, (i + 1) * 2 + pref_count[r + 1][y] - pref_count[l][y])
	return best
tc = int(input())
res = []
for _ in range(tc):
	n = int(input())
	a = list(map(int, input().split()))
	res.append(solve(a))
print('\n'.join(map(str, res)))


tc = int(input())
for ll in range(tc):
	l = int(input())
	s = list(map(int, input().split()))
	arr = [[0] * (l + 1) for i in range(201)]
	su = [[] for i in range(201)]
	for j in range(l):
		for i in range(1, 201):
			arr[i][j + 1] = arr[i][j]
		arr[s[j]][j + 1] = arr[s[j]][j] + 1
		su[s[j]].append(j + 1)
	ans = 1
	for i in range(1, 201):
		if len(su[i]) > 1:
			for k in range(len(su[i]) // 2):
				cur = (k + 1) * 2
				for j in range(1, 201):
					newans = cur + arr[j][su[i][len(su[i]) - 1 - k]] - arr[j][su[i][k]]
					if i == j:
						newans -= 1
					ans = max(newans, ans)
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	maxi = 0
	index = {}
	s = list(set(a))
	n1 = len(s)
	index = [[] for i in range(201)]
	for i in range(n):
		index[a[i]].append(i)
	maxi = 0
	pref = [[0] * n for i in range(201)]
	for i in range(201):
		suma = 0
		for j in range(n):
			if a[j] == i:
				suma += 1
			pref[i][j] = suma
	for i in range(201):
		j1 = 0
		n2 = len(index[i])
		j2 = n2 - 1
		for j in range(n2 // 2):
			cnt = 2 * (j + 1)
			maxi1 = 0
			for itr in range(201):
				maxi1 = max(maxi1, pref[itr][index[i][j2] - 1] - pref[itr][index[i][j1]])
			maxi = max(maxi, maxi1 + cnt)
			j1 += 1
			j2 -= 1
	for i in range(201):
		maxi = max(maxi, len(index[i]))
	sys.stdout.write(str(maxi) + '\n')


def find_leftmost_right(a, k):
	return indices[a - 1][-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] - 1].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)


from sys import stdin, gettrace

def input():
	return stdin.buffer.readline()
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] - 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(200)))
			result = max(result, 2 * c + mr)
	print(result)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	x = [[] for _ in range(201)]
	cnt = [[0] * (n + 1) for _ in range(201)]
	for i in range(n):
		cnt[a[i]][i + 1] += 1
		x[a[i]].append(i)
	for i in range(1, 201):
		for j in range(1, n + 1):
			cnt[i][j] += cnt[i][j - 1]
	ans = 1
	for i in range(201):
		x0 = x[i]
		if not x0:
			continue
		(l, r) = (0, len(x0) - 1)
		now = 0
		while l < r:
			now += 1
			(l0, r0) = (x0[l], x0[r])
			m = 0
			for j in range(201):
				c = cnt[j][r0] - cnt[j][l0 + 1]
				if m < c:
					m = c
			if ans < 2 * now + m:
				ans = 2 * now + m
			l += 1
			r -= 1
	print(ans)


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)


from sys import stdin, gettrace

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

def main():

	def solve():
		n = int(input())
		aa = [int(a) - 1 for a in input().split()]
		counts = [[0] * 200]
		pos = [[] for _ in range(200)]
		for (i, a) in enumerate(aa):
			counts.append(counts[-1].copy())
			counts[-1][a] += 1
			pos[a].append(i)
		mx = 0
		for (i, a) in enumerate(aa):
			ca = counts[i + 1][a]
			ps = pos[a][-ca]
			if ps > i:
				for b in range(200):
					mx = max(counts[ps][b] - counts[i + 1][b] + ca * 2, mx)
			elif ps == i:
				mx = max(ca * 2 - 1, mx)
		print(mx)
	q = int(input())
	for _ in range(q):
		solve()
main()


from sys import stdin, stdout

def write(_s):
	stdout.write(_s)

def writeint(_s):
	stdout.write(str(_s))

def writelist(_l):
	stdout.write(' '.join(_l))

def read():
	return stdin.readline().strip().split(' ')

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

def readints():
	return map(lambda x: int(x) - 1, stdin.readline().strip().split(' '))
limit = 200

def solve():
	n = readint()
	a = list(readints())
	indices = [[] for _ in range(limit)]
	prefs = [[0] * limit]
	for (i, el) in enumerate(a):
		indices[el].append(i)
		pref = list(prefs[-1])
		pref[el] += 1
		prefs.append(pref)
	longest = max(prefs[-1])
	for (i, el) in enumerate(a):
		el = a[i]
		current_len = prefs[i][el] + 1
		other = indices[el][-current_len]
		if other <= i:
			continue
		for el2 in range(limit):
			if el == el2:
				continue
			total = prefs[other][el2]
			if total > 0:
				elements_range = total - prefs[i + 1][el2]
				longest = max(longest, current_len * 2 + elements_range)
	return longest
t = readint()
while t:
	res = solve()
	writeint(res)
	write('\n')
	t -= 1


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)


import sys
import math
input = sys.stdin.readline
from functools import cmp_to_key

def pi():
	return int(input())

def pl():
	return int(input(), 16)

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

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

def invr():
	return map(int, input().split())
mod = 1000000007
f = []

def fact(n, m):
	global f
	f = [1 for i in range(n + 1)]
	f[0] = 1
	for i in range(1, n + 1):
		f[i] = f[i - 1] * i % m

def fast_mod_exp(a, b, m):
	res = 1
	while b > 0:
		if b & 1:
			res = res * a % m
		a = a * a % m
		b = b >> 1
	return res

def inverseMod(n, m):
	return fast_mod_exp(n, m - 2, m)

def ncr(n, r, m):
	if r == 0:
		return 1
	return f[n] * inverseMod(f[n - r], m) % m * inverseMod(f[r], m) % m

def main():
	E2()

def xdfs(root, v, sub, parent):
	st = [root]
	while len(st) > 0:
		node = st.pop()
		for i in range(len(v[node])):
			if v[node][i] != node:
				st.append(v[node][i])

def X():
	try:
		t = pi()
		while t:
			t -= 1
			n = pi()
			v = [[] for i in range(n)]
			for i in range(n - 1):
				[x, y] = ti()
				v[x - 1].append(y - 1)
				v[y - 1].append(x - 1)
			m = pi()
			p = ti()
			e = [0 for i in range(n - 1)]
			sub = [0 for i in range(n)]
			dfs(0, v, sub, -1)
			for i in range(1, n):
				e[i - 1] = sub[i] * (n - sub[i])
			if len(p) < n - 1:
				while len(p) < n - 1:
					p.append(1)
			p = sorted(p)
			if len(p) > n - 1:
				x = 1
				for i in range(n - 2, len(p)):
					x = x * p[i]
				while len(p) > n - 2:
					p.pop()
				p.append(x)
			e = sorted(e)
			res = 0
			for i in range(n - 1):
				res = (res + p[i] * e[i]) % mod
			print(res)
	except:
		print(sys.exc_info())

def bfs(v, root):
	q = [root, None]
	l = 0
	visited = [0 for i in range(len(v))]
	dist = [0 for i in range(len(v))]
	while len(q) > 0:
		node = q.pop(0)
		if node is not None:
			visited[node] = 1
			dist[node] = l
			for i in range(len(v[node])):
				if visited[v[node][i]] == 0:
					visited[v[node][i]] = 1
					q.append(v[node][i])
		else:
			l += 1
			if len(q) != 0:
				q.append(None)
	return dist

def B():
	n = pi()
	v = [[] for i in range(n)]
	for i in range(n - 1):
		[x, y] = ti()
		v[x - 1].append(y - 1)
		v[y - 1].append(x - 1)
	leafs = []
	for i in range(n):
		if len(v[i]) == 1:
			leafs.append(i)
	mn = 1
	d = bfs(v, leafs[0])
	for i in range(1, len(leafs)):
		if d[leafs[i]] % 2 != 0:
			mn = 3
			break
	count = 0
	for i in range(n):
		f = 0
		for j in range(len(v[i])):
			if len(v[v[i][j]]) == 1:
				f = 1
				break
		if f:
			count += 1
	mx = n - 1 - len(leafs) + count
	print(mn, mx)

def E2():
	t = pi()
	while t:
		t -= 1
		(n, a) = (pi(), ti())
		if n == 1:
			print(1)
			continue
		pz = [[] for i in range(200)]
		counts = [[0 for j in range(200)] for i in range(n)]
		for i in range(n):
			for j in range(200):
				if a[i] - 1 == j:
					counts[i][j] = counts[i - 1][j] + 1 if i != 0 else 1
					pz[j].append(i)
				else:
					counts[i][j] = counts[i - 1][j] if i != 0 else 0
		res = 1
		for i in range(200):
			for sz in range(1, n + 1):
				if len(pz[i]) >= 2 * sz:
					st = pz[i][sz - 1]
					en = pz[i][len(pz[i]) - sz]
					mx = 0
					for j in range(200):
						mx = max(mx, counts[en - 1][j] - counts[st][j])
					res = max(res, mx + 2 * sz)
		print(res)
main()


from operator import itemgetter
import sys
input = sys.stdin.readline
MAX_A = 200
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ruiseki = [[0] * MAX_A for i in range(n + 1)]
	for i in range(n):
		for j in range(MAX_A):
			ruiseki[i + 1][j] = ruiseki[i][j]
			if a[i] - 1 == j:
				ruiseki[i + 1][j] += 1
	ans = 0
	for num in set(a):
		l = 0
		r = n - 1
		cnt = 0
		while True:
			while True:
				if a[l] != num:
					l += 1
				else:
					break
			while True:
				if a[r] != num:
					r -= 1
				else:
					break
			if l == r:
				ans = max(ans, cnt + 1)
				break
			elif l > r:
				break
			cnt += 1
			tmp_max = 0
			for j in range(MAX_A):
				tmp_max = max(tmp_max, ruiseki[r][j] - ruiseki[l + 1][j])
			ans = max(ans, cnt * 2 + tmp_max)
			l += 1
			r -= 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = [int(i) for i in input().split()]
	prev = [[0] * 201] * n
	pos = [[] for i in range(201)]
	for i in range(n):
		prev[i] = prev[i - 1].copy()
		prev[i][s[i]] += 1
		pos[s[i]].append(i)
	ans = 0
	for i in range(201):
		ans = max(ans, len(pos[i]))
		for j in range(1, len(pos[i]) // 2 + 1):
			m = 0
			for k in range(201):
				m = max(m, prev[pos[i][-j] - 1][k] - prev[pos[i][j - 1]][k])
			ans = max(ans, m + 2 * j)
	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 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 sys import stdin
import sys
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	arr = list(map(int, stdin.readline().split()))
	dp = [[0] * (n + 1) for i in range(200)]
	pos = [[] for i in range(200)]
	for i in range(n):
		for c in range(200):
			dp[c][i + 1] = dp[c][i]
		dp[arr[i] - 1][i + 1] += 1
		pos[arr[i] - 1].append(i)
	ans = 0
	for i in range(200):
		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(200):
				res = dp[k][r + 1] - dp[k][l]
				ans = max(ans, 2 * (j + 1) + res)
	print(ans)