This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on $n$ are greater than in the easy version of the problem.

You are given an array $a$ of $n$ integers (the given array can contain equal elements). You can perform the following operations on array elements:  choose any index $i$ ($1 \le i \le n$) and move the element $a[i]$ to the begin of the array;  choose any index $i$ ($1 \le i \le n$) and move the element $a[i]$ to the end of the array. 

For example, if $n = 5$, $a = [4, 7, 2, 2, 9]$, then the following sequence of operations can be performed:   after performing the operation of the first type to the second element, the array $a$ will become $[7, 4, 2, 2, 9]$;  after performing the operation of the second type to the second element, the array $a$ will become $[7, 2, 2, 9, 4]$. 

You can perform operations of any type any number of times in any order.

Find the minimum total number of operations of the first and second type that will make the $a$ array sorted in non-decreasing order. In other words, what is the minimum number of operations must be performed so the array satisfies the inequalities $a[1] \le a[2] \le \ldots \le a[n]$.


-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the test. Then $t$ test cases follow.

Each test case starts with a line containing an integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the size of the array $a$.

Then follow $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — an array that needs to be sorted by the given operations. The given array can contain equal elements.

The sum of $n$ for all test cases in one test does not exceed $2 \cdot 10^5$.


-----Output-----

For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.


-----Example-----
Input
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9

Output
2
2
0
0
1
1
1
1
16



-----Note-----

In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: $[4, 7, 2, 2, 9] \rightarrow [2, 4, 7, 2, 9] \rightarrow [2, 2, 4, 7, 9]$.

In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: $[3, 5, 8, 1, 7] \rightarrow [1, 3, 5, 8, 7] \rightarrow [1, 3, 5, 7, 8]$.

In the third test case, the array is already sorted.

Difficulty: VERY_HARD

Solutions:
from sys import stdin
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	id = list(zip(l, list(range(n))))
	id.sort()
	(val, pos) = zip(*id)
	blok = []
	cur = [pos[0]]
	for i in range(1, n):
		if val[i] == val[i - 1]:
			cur.append(pos[i])
		else:
			cur.sort()
			blok.append(cur)
			cur = [pos[i]]
	cur.sort()
	blok.append(cur)
	best = 0
	m = len(blok)
	for j in range(m):
		best = max(len(blok[j]), best)
	i = 0
	while True:
		if i >= m - 2:
			break
		cyk = min(blok[i + 1])
		j = -1
		while j + 1 < len(blok[i]) and blok[i][j + 1] < cyk:
			j += 1
		su = j + 1
		ii = i + 2
		while ii < m:
			if min(blok[ii]) > max(blok[ii - 1]):
				su += len(blok[ii - 1])
				ii += 1
			else:
				break
		if ii == m:
			su += len(blok[-1])
			best = max(best, su)
		else:
			xxx = max(blok[ii - 1])
			su += len(blok[ii - 1])
			inde = len(blok[ii]) - 1
			while inde >= 0 and blok[ii][inde] >= xxx:
				su += 1
				inde -= 1
			best = max(best, su)
		i = max(i + 1, ii - 1)
	for i in range(1, m):
		b1 = blok[i]
		b0 = blok[i - 1]
		(l0, l1, i1) = (len(b0), len(b1), 0)
		for ind in range(l0):
			while True:
				if i1 < l1 and b1[i1] <= b0[ind]:
					i1 += 1
				else:
					break
			if l1 == i1:
				break
			best = max(best, ind + 1 + (l1 - i1))
	print(n - best)


class seq:

	def __init__(self, l, c):
		self.length = l
		self.final_ctr = c
import copy
t = int(input())
for _ in range(t):
	n = int(input())
	d = {}
	c = {}
	prev = {}
	ctr = {}
	li = [int(i) for i in input().split(' ')]
	n = len(li)
	for i in li:
		ctr[i] = ctr.get(i, 0) + 1
	so = sorted(ctr)
	pp = -1
	for i in so:
		prev[i] = pp
		pp = i
	mx = 1
	for i in li:
		if i in d:
			if prev[i] in d and d[prev[i]][1].final_ctr == ctr[prev[i]]:
				if d[prev[i]][1].length > max(d[i][1].length, d[i][0].length):
					d[i][0].length = d[prev[i]][1].length
					d[i][0].final_ctr = 0
			if c.get(prev[i], 0) > max(d[i][1].length, d[i][0].length):
				d[i][0].length = c[prev[i]]
				d[i][0].final_ctr = 0
			d[i][1].final_ctr += 1
			d[i][1].length += 1
			d[i][0].final_ctr += 1
			d[i][0].length += 1
		else:
			d.setdefault(i, [seq(0, 0), seq(0, 0)])
			if prev[i] in d:
				if d[prev[i]][1].final_ctr == ctr[prev[i]]:
					d[i][1] = seq(d[prev[i]][1].length + 1, 1)
					d[i][0] = seq(d[prev[i]][1].length + 1, 1)
					if c.get(prev[i], 0) > d[i][1].length:
						d[i][1].length = c[prev[i]] + 1
						d[i][0].length = c[prev[i]] + 1
						d[i][1].final_ctr = 1
						d[i][0].final_ctr = 1
				else:
					d[i][1] = seq(c[prev[i]] + 1, 1)
					d[i][0] = seq(c[prev[i]] + 1, 1)
			else:
				d[i][1] = seq(1, 1)
		mx = max(mx, d[i][1].length, d[i][0].length)
		c[i] = c.get(i, 0) + 1
	print(n - mx)


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_a = [0] * t
	for ti in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		comp_dict = {x: i for (i, x) in enumerate(sorted(set(a)))}
		cnt = [0] * n
		max_cnt = [0] * n
		for i in range(n):
			a[i] = comp_dict[a[i]]
			max_cnt[a[i]] += 1
		dp = [[0] * 3 for _ in range(n + 1)]
		for cur in a:
			dp[cur][2] += 1
			if cnt[cur - 1] == max_cnt[cur - 1]:
				dp[cur][2] = max(dp[cur][2], dp[cur - 1][1] + 1)
			dp[cur][2] = max(dp[cur][2], dp[cur - 1][0] + 1)
			if cnt[cur] == 0:
				if cnt[cur - 1] == max_cnt[cur - 1]:
					dp[cur][1] = max(dp[cur][1], dp[cur - 1][1] + 1)
			else:
				dp[cur][1] += 1
			if cnt[cur] == 0:
				dp[cur][1] = max(dp[cur][1], dp[cur - 1][0] + 1)
			dp[cur][0] += 1
			cnt[cur] += 1
		ans_a[ti] = n - max((dp[i][-1] for i in range(n)))
	sys.stdout.buffer.write(('\n'.join(map(str, ans_a)) + '\n').encode('utf-8'))
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')

class seq:

	def __init__(self, l, c):
		self.length = l
		self.final_ctr = c
t = int(input())
for _ in range(t):
	n = int(input())
	d = {}
	c = {}
	prev = {}
	ctr = {}
	li = [int(i) for i in input().split(' ')]
	n = len(li)
	for i in li:
		ctr[i] = ctr.get(i, 0) + 1
	so = sorted(ctr)
	pp = -1
	for i in so:
		prev[i] = pp
		pp = i
	mx = 1
	for i in li:
		if i in d:
			if prev[i] in d and d[prev[i]][1].final_ctr == ctr[prev[i]]:
				if d[prev[i]][1].length > max(d[i][1].length, d[i][0].length):
					d[i][0].length = d[prev[i]][1].length
					d[i][0].final_ctr = 0
			if c.get(prev[i], 0) > max(d[i][1].length, d[i][0].length):
				d[i][0].length = c[prev[i]]
				d[i][0].final_ctr = 0
			d[i][1].final_ctr += 1
			d[i][1].length += 1
			d[i][0].final_ctr += 1
			d[i][0].length += 1
		else:
			d.setdefault(i, [seq(0, 0), seq(0, 0)])
			if prev[i] in d:
				if d[prev[i]][1].final_ctr == ctr[prev[i]]:
					d[i][1] = seq(d[prev[i]][1].length + 1, 1)
					d[i][0] = seq(d[prev[i]][1].length + 1, 1)
					if c.get(prev[i], 0) > d[i][1].length:
						d[i][1].length = c[prev[i]] + 1
						d[i][0].length = c[prev[i]] + 1
						d[i][1].final_ctr = 1
						d[i][0].final_ctr = 1
				else:
					d[i][1] = seq(c[prev[i]] + 1, 1)
					d[i][0] = seq(c[prev[i]] + 1, 1)
			else:
				d[i][1] = seq(1, 1)
		mx = max(mx, d[i][1].length, d[i][0].length)
		c[i] = c.get(i, 0) + 1
	print(n - mx)


import sys

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

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	n = mint()
	b = [None] * n
	i = 0
	for v in mints():
		b[i] = (v, i)
		i += 1
	b.sort()
	c = [0] * n
	ans = int(1000000000.0)
	s = None
	i = 0
	while i < n:
		j = i + 1
		v = b[i][0]
		while j < n and b[j][0] == v:
			j += 1
		if s is None:
			for z in range(i, j):
				c[z] = j - z - 1
			ans = n - j
		else:
			k = s
			while k < e and b[k][1] < b[i][1]:
				k += 1
			for z in range(i, j - 1):
				c[z] = j - z - 1 + e
			if k == e:
				c[j - 1] = c[e - 1]
			else:
				c[j - 1] = s + e - k
			v = n - i - j
			for z in range(i, j):
				while k < e and b[k][1] < b[z][1]:
					k += 1
				ans = min(ans, z + (e if k == s else c[k - 1]) + v)
		(s, e, i) = (i, j, j)
	print(ans)
for i in range(mint()):
	solve()


from sys import stdin, stdout

def flying_sort(n, a):
	b = sorted(a)
	dic = {}
	seq = 1
	dic[b[0]] = seq
	num = [0 for i in range(n + 1)]
	head = [0 for i in range(n + 1)]
	tail = [-1 for i in range(n + 1)]
	pos = [0 for i in range(n + 1)]
	for i in range(1, len(b)):
		if b[i] != b[i - 1]:
			seq += 1
			dic[b[i]] = seq
	for i in range(len(a)):
		a[i] = dic[a[i]]
		num[a[i]] += 1
		tail[a[i]] = i + 1
		if head[a[i]] == 0:
			head[a[i]] = i + 1
	dp = [[0, 0, 0] for i in range(n + 1)]
	maxseq = 0
	for i in range(1, n + 1):
		v = a[i - 1]
		dp[i][0] = dp[pos[v]][0] + 1
		dp[i][1] = max(dp[pos[v]][1] + 1, dp[pos[v - 1]][0] + 1, dp[pos[v - 1]][2] + 1)
		if tail[v] == i:
			dp[i][2] = dp[head[v]][1] + num[v] - 1
		pos[v] = i
		for k in range(3):
			maxseq = max(maxseq, dp[i][k])
	res = len(a) - maxseq
	return res
t = int(stdin.readline())
for i in range(t):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	stdout.write(str(flying_sort(n, a)) + '\n')


from collections import defaultdict
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l2 = sorted(list(set(l)))
	d = defaultdict(int)
	ind = [[-1] * 2 for i in range(len(l2))]
	num = [0] * len(l2)
	pos = [0] * len(l2)
	for i in range(len(l2)):
		d[l2[i]] = i
	cl = [-1]
	for i in range(n):
		x = d[l[i]]
		cl.append(x)
		num[x] += 1
		if ind[x][0] == -1:
			ind[x][0] = i + 1
		ind[x][1] = i + 1
	dp = [[0] * 3 for i in range(n + 1)]
	for i in range(1, n + 1):
		x = cl[i]
		dp[i][0] = dp[pos[x]][0] + 1
		if x == 0:
			dp[i][1] = dp[pos[x]][1] + 1
		else:
			dp[i][1] = max(dp[pos[x]][1], dp[pos[x - 1]][0], dp[pos[x - 1]][2]) + 1
		if i == ind[x][1]:
			dp[i][2] = dp[ind[x][0]][1] + num[x] - 1
		pos[x] = i
	ans = 0
	for i in dp:
		ans = max(ans, max(i))
	print(n - ans)


import os
import sys
from io import BytesIO, IOBase

def main():

	def comprs(a):
		d = {}
		b = [x for x in a]
		b.sort()
		(pvr, i) = (-1, 0)
		for x in b:
			if pvr == x:
				continue
			pvr = x
			d[x] = i
			i += 1
		a = [d[x] for x in a]
		return (i, a)
	for _ in range(int(input())):
		n = int(input())
		a = [int(x) for x in input().split()]
		(m, a) = comprs(a)
		ans = 0
		idx = [[] for _ in range(m)]
		for (i, x) in enumerate(a):
			idx[x].append(i)
		dp = (n, 0)
		for p in reversed(range(m)):
			cur = idx[p]
			if dp[0] > cur[-1]:
				dp = (cur[0], len(cur) + dp[1])
			else:
				for (i, x) in enumerate(cur):
					if x > dp[0]:
						ans = max(ans, dp[1] + i)
						break
				cnt = len(cur) + len(idx[p + 1])
				for x in idx[p + 1]:
					if x > cur[-1]:
						break
					cnt -= 1
				dp = (cur[0], cnt)
		ans = max(ans, dp[1])
		for p in reversed(range(m - 1)):
			j = 0
			for (i, x) in enumerate(idx[p]):
				while j < len(idx[p + 1]) and x > idx[p + 1][j]:
					j += 1
				ans = max(ans, i + 1 + len(idx[p + 1]) - j)
		print(n - 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()


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 gcd, ceil

def prod(a, mod=10 ** 9 + 7):
	ans = 1
	for each in a:
		ans = ans * each % mod
	return ans

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

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	n = int(input())
	a = list(map(int, input().split()))
	se = sorted(list(set(a)))
	di = {}
	for i in range(len(se)):
		di[se[i]] = i + 1
	a = [di[k] for k in a]
	count = [0] * (n + 1)
	for i in a:
		count[i] += 1
	c = [0] * (n + 1)
	(seen, now) = ([-1] * (n + 1), [-1] * (n + 1))
	dp = [0] * n
	ans = 0
	for i in range(n):
		cur = a[i]
		dp[i] = max(dp[i], c[cur - 1] + 1)
		if seen[cur] != -1:
			dp[i] = max(dp[i], dp[seen[cur] if seen[cur] != -1 else 0] + 1)
		if c[cur - 1] == count[cur - 1]:
			dp[i] = max(dp[i], dp[now[cur - 1] if now[cur - 1] != -1 else 0] + c[cur - 1])
		c[cur] += 1
		seen[cur] = i
		if now[cur] == -1:
			now[cur] = i
	print(n - max(dp))


from collections import defaultdict
import bisect

def read_list():
	return list(map(int, input().strip().split(' ')))

def print_list(l):
	print(' '.join(map(str, l)))
N = int(input())
for _ in range(N):
	n = int(input())
	nums = read_list()
	dic = defaultdict(list)
	for i in range(n):
		dic[nums[i]].append(i)
	data = list(set(nums))
	data.sort()
	l = len(data)
	res = 0
	if l > 1:
		ind = bisect.bisect_left(dic[data[0]], dic[data[1]][0])
		ln = len(dic[data[1]])
		for j in range(len(dic[data[0]]) - 1, ind - 1, -1):
			res = max(res, j + 1 + ln - bisect.bisect_left(dic[data[1]], dic[data[0]][j]))
		tmp = ind + ln
	else:
		tmp = 0
	for i in range(2, l):
		if dic[data[i]][0] > dic[data[i - 1]][-1]:
			tmp += len(dic[data[i]])
		else:
			res = max(res, tmp + len(dic[data[i]]) - bisect.bisect_left(dic[data[i]], dic[data[i - 1]][-1]))
			ind = bisect.bisect_left(dic[data[i - 1]], dic[data[i]][0])
			ln = len(dic[data[i]])
			for j in range(len(dic[data[i - 1]]) - 1, ind - 1, -1):
				res = max(res, j + 1 + ln - bisect.bisect_left(dic[data[i]], dic[data[i - 1]][j]))
			tmp = ind + ln
	res = max(res, tmp)
	for a in list(dic.values()):
		res = max(len(a), res)
	print(n - res)


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()):
		inf = 10 ** 9
		n = II()
		aa = LI()
		s = set(aa)
		enc = {a: i for (i, a) in enumerate(sorted(s))}
		aa = [enc[a] for a in aa]
		first = [False] * n
		fin = [False] * len(s)
		for i in range(n):
			if fin[aa[i]]:
				continue
			first[i] = True
			fin[aa[i]] = True
		end = [False] * n
		fin = [False] * len(s)
		for i in range(n - 1, -1, -1):
			if fin[aa[i]]:
				continue
			end[i] = True
			fin[aa[i]] = True
		last = [-1] * len(s)
		dp = [[0] * 3 for _ in range(n)]
		mx = 0
		for (i, a) in enumerate(aa):
			val = 1
			i0 = last[a]
			if i0 != -1:
				val = dp[i0][0] + 1
			dp[i][0] = val
			mx = max(mx, val)
			val = -inf
			if i0 != -1:
				val = dp[i0][1] + 1
			i1 = -1
			if a:
				i1 = last[a - 1]
			if i1 != -1:
				if first[i]:
					val = max(val, dp[i1][0] + 1)
				if end[i1] and first[i]:
					val = max(val, dp[i1][1] + 1)
			dp[i][1] = val
			mx = max(mx, val)
			val = -inf
			if i0 != -1:
				val = dp[i0][2] + 1
			if i1 != -1:
				val = max(val, dp[i1][0] + 1)
				if end[i1]:
					val = max(val, dp[i1][1] + 1)
			dp[i][2] = val
			mx = max(mx, val)
			last[a] = i
		print(n - mx)
main()


import collections
import string

def listprint(l):
	if len(l) == 0:
		print('[]')
		return
	s = '[ ' + '{0:<2}'.format(l[0])
	for i in range(1, len(l)):
		s += ', ' + '{0:>2}'.format(l[i])
	s += ' ]'
	print(s)

def main():
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a)
	d = collections.defaultdict(list)
	f = collections.defaultdict(list)
	for i in range(n - 1, -1, -1):
		d[b[i]].append(i)
	tmp = []
	for i in range(n):
		whereInB = d[a[i]][-1]
		if a[i] in f:
			z = 1 + f[a[i]][-1]
			if whereInB != 0 and b[whereInB - 1] in f:
				prevNumberList = f[b[whereInB - 1]]
				p = prevNumberList
				if len(p) == len(d[b[whereInB - 1]]):
					z = max(z, p[0] + len(p))
				else:
					z = max(z, 1 + len(p))
			f[a[i]].append(z)
			tmp.append(f[a[i]][-1])
			continue
		if whereInB == 0 or b[whereInB - 1] not in f:
			f[a[i]].append(1)
		elif len(d[b[whereInB - 1]]) == len(f[b[whereInB - 1]]):
			prevNumberList = f[b[whereInB - 1]]
			p = prevNumberList
			f[a[i]].append(p[0] + len(p))
		else:
			f[a[i]].append(1 + len(f[b[whereInB - 1]]))
		tmp.append(f[a[i]][-1])
	print(n - max(map(max, f.values())))
tn = int(input())
for _ in range(tn):
	main()


for t in range(int(input())):
	n = int(input())
	aa = list(map(int, input().split(' ')))
	asort = sorted([(v, i) for (i, v) in enumerate(aa)])
	inds = {}
	for (a, ai) in asort:
		if a not in inds:
			inds[a] = []
		inds[a] += [ai]

	def left_eq(b, i):
		binds = inds[b]
		l = -1
		r = len(binds) - 1
		while l < r:
			m = (l + r + 1) // 2
			if binds[m] < i:
				l = m
			else:
				r = m - 1
		return l + 1

	def right_eq(b, i):
		binds = inds[b]
		l = 0
		r = len(binds)
		while l < r:
			m = (l + r) // 2
			if binds[m] > i:
				r = m
			else:
				l = m + 1
		return len(binds) - l
	ls = [None] * n
	for (i, (a, ai)) in enumerate(asort):
		if i == 0:
			ls[ai] = 1
			continue
		if asort[i - 1][1] < ai:
			curl = ls[asort[i - 1][1]] + 1
		else:
			curl = left_eq(asort[i - 1][0], ai) + 1
		ls[ai] = curl
	for (i, (a, ai)) in reversed(list(enumerate(asort))):
		if i == n - 1:
			continue
		if asort[i + 1][0] != a:
			ls[ai] += right_eq(asort[i + 1][0], ai)
	alter = [-10]
	values = list(inds.keys())
	v2vi = {v: i for (i, v) in enumerate(values)}
	for (i, (a, ai)) in enumerate(asort):
		avin = v2vi[a]
		if avin > 0:
			alter += [left_eq(values[avin - 1], ai) + 1 + right_eq(a, ai)]
	maxSeqLen = max(max(ls), max(alter))
	print(n - maxSeqLen)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	p = []
	for i in range(n):
		p.append((a[i], i))
	p.sort(key=lambda x: x[0])
	aOrder = [-1] * n
	curIndex = 0
	for i in range(n):
		if i >= 1 and p[i][0] != p[i - 1][0]:
			curIndex += 1
		aOrder[p[i][1]] = curIndex
	aCount = [0] * (curIndex + 1)
	for i in range(n):
		aCount[aOrder[i]] += 1
	maxSubseq0 = [0] * (curIndex + 1)
	maxSubseq1 = [0] * (curIndex + 1)
	maxSubseq2 = [0] * (curIndex + 1)
	maxSubseq3 = [0] * (curIndex + 1)
	for i in range(n):
		aCurOrder = aOrder[i]
		curSubseq1 = maxSubseq1[aCurOrder] + 1
		curSubseq2 = maxSubseq2[aCurOrder] + 1
		curSubseq3 = maxSubseq3[aCurOrder] + 1
		if curSubseq1 == 1:
			curSubseq1 = 0
			curSubseq2 = 0
		if curSubseq3 == 1:
			curSubseq3 = 0
		maxSubseq0[aCurOrder] += 1
		justUpdated = False
		if aCurOrder >= 1 and maxSubseq0[aCurOrder - 1] > 0:
			if curSubseq1 == 0:
				curSubseq1 = maxSubseq0[aCurOrder - 1] + 1
				curSubseq2 = 1
				justUpdated = True
			elif curSubseq1 < maxSubseq0[aCurOrder - 1] + 1 and curSubseq3 < maxSubseq0[aCurOrder - 1] + 1:
				curSubseq3 = maxSubseq0[aCurOrder - 1] + 1
		if aCurOrder >= 1 and maxSubseq1[aCurOrder - 1] > 0 and (maxSubseq2[aCurOrder - 1] == aCount[aCurOrder - 1]):
			if curSubseq1 == 0 or justUpdated:
				curSubseq1 = maxSubseq1[aCurOrder - 1] + 1
				curSubseq2 = 1
			elif curSubseq1 < maxSubseq1[aCurOrder - 1] + 1 and curSubseq3 < maxSubseq1[aCurOrder - 1] + 1:
				curSubseq3 = maxSubseq1[aCurOrder - 1] + 1
		maxSubseq1[aCurOrder] = curSubseq1
		maxSubseq2[aCurOrder] = curSubseq2
		maxSubseq3[aCurOrder] = curSubseq3
	print(n - max(maxSubseq0 + maxSubseq1 + maxSubseq3))