This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on $n$ are less than in the hard version of the problem.

You are given an array $a$ of $n$ integers (there are no equals elements in the array). 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, 3, 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, 3, 9]$;  after performing the operation of the second type to the second element, the array $a$ will become $[7, 2, 3, 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 that 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 100$) — 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 3000$) — length 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. All numbers in the given array are distinct.

The sum of $n$ for all test cases in one test does not exceed $3000$.


-----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
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3

Output
2
2
0
2



-----Note-----

In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: $[4, 7, 2, 3, 9] \rightarrow [3, 4, 7, 2, 9] \rightarrow [2, 3, 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: HARD
Tags: Dynamic programming

Amortized analysis

Greedy algorithms
Skill types: Dynamic programming

Amortized analysis

Greedy algorithms

Starter code:

Solutions:
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)


def search(lis, idx, val):
	low = 0
	high = idx
	while low <= high:
		mid = (low + high) // 2
		if lis[mid] == val:
			return mid
		if lis[mid] > val:
			high = mid - 1
		else:
			low = mid + 1

def ans(arr):
	hj = 9
	ghkd = 898291
	lis_f = sorted(arr)
	ans_arr = [0] * len(arr)
	for i in range(len(arr)):
		ans_arr[search(lis_f, len(arr) - 1, arr[i])] = i
	c = 1
	p = 0
	for j in range(1, len(arr)):
		if ans_arr[j] > ans_arr[j - 1]:
			c += 1
		elif c > p:
			p = c
			ghkd = 898291
			c = 1
		else:
			c = 1
	if c > p:
		p = c
	print(len(arr) - p)
k = int(input())
for i in range(k):
	input()
	l = list(map(int, input().split()))
	ans(l)


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
input = stdin.readline
t = int(input())
for _ in range(t):
	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 = len(b0)
		l1 = len(b1)
		i1 = 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)


from bisect import bisect_left, bisect_right

class Result:

	def __init__(self, index, value):
		self.index = index
		self.value = value

class BinarySearch:

	def __init__(self):
		pass

	@staticmethod
	def greater_than(num: int, func, size: int=1):
		if isinstance(func, list):
			index = bisect_right(func, num)
			if index == len(func):
				return Result(None, None)
			else:
				return Result(index, func[index])
		else:
			(alpha, omega) = (0, size - 1)
			if func(omega) <= num:
				return Result(None, None)
			while alpha < omega:
				if func(alpha) > num:
					return Result(alpha, func(alpha))
				if omega == alpha + 1:
					return Result(omega, func(omega))
				mid = (alpha + omega) // 2
				if func(mid) > num:
					omega = mid
				else:
					alpha = mid

	@staticmethod
	def less_than(num: int, func, size: int=1):
		if isinstance(func, list):
			index = bisect_left(func, num) - 1
			if index == -1:
				return Result(None, None)
			else:
				return Result(index, func[index])
		else:
			(alpha, omega) = (0, size - 1)
			if func(alpha) >= num:
				return Result(None, None)
			while alpha < omega:
				if func(omega) < num:
					return Result(omega, func(omega))
				if omega == alpha + 1:
					return Result(alpha, func(alpha))
				mid = (alpha + omega) // 2
				if func(mid) < num:
					alpha = mid
				else:
					omega = mid
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
bs = BinarySearch()
for _ in range(int(input()) if True else 1):
	n = int(input())
	a = list(map(int, input().split()))
	di = {}
	for i in range(n):
		if a[i] not in di:
			di[a[i]] = []
		di[a[i]] += [i]
	se = sorted(list(set(a)))
	ans = 0
	cn = [1] * n
	for i in range(len(se) - 1, -1, -1):
		if i == len(se) - 1:
			for j in range(len(di[se[i]])):
				cn[di[se[i]][j]] = len(di[se[i]]) - j
			continue
		cur = se[i]
		for j in range(len(di[cur]) - 1, -1, -1):
			if j != len(di[cur]) - 1:
				cn[di[cur][j]] = len(di[cur]) - j + cn[di[cur][-1]] - 1
			val = bs.greater_than(di[cur][j], di[se[i + 1]]).value
			val2 = bs.less_than(di[cur][j], di[se[i + 1]]).value
			if val is not None and val2 is None:
				cn[di[cur][j]] = max(cn[di[cur][j]], cn[val] + 1)
			elif val is not None:
				ind = bs.greater_than(di[cur][j], di[se[i + 1]]).index
				cn[di[cur][j]] = max(cn[di[cur][j]], 1 + len(di[se[i + 1]]) - ind)
	print(n - max(cn))


from sys import stdin, stdout

def findops(l):
	ans = 0
	count = 1
	for i in range(1, len(l)):
		if l[i] > l[i - 1]:
			count += 1
		else:
			ans = max(ans, count)
			count = 1
	return len(l) - max(ans, count)
for _ in range(int(stdin.readline())):
	stdin.readline()
	l = list(map(int, stdin.readline().split()))
	print(findops(sorted(range(len(l)), key=lambda x: l[x])))


def some_random_function():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function5():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)
import os, sys
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(lambda xx: [int(xx), 0], input().split()))
		for ind in range(n):
			a[ind][1] = ind
		b = sorted(a, key=lambda xx: xx[0])
		(prev, maxi, cou) = (-1, 0, 0)
		for i in b:
			if i[1] > prev:
				cou += 1
			else:
				maxi = max(maxi, cou)
				cou = 1
			prev = i[1]
		maxi = max(maxi, cou)
		print(n - maxi)
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')

def some_random_function1():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function2():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function3():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function4():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function6():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function7():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function8():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)
main()


t = int(input())
for _ in range(t):
	n = int(input())
	l = [[x, i] for (i, x) in enumerate(map(int, input().split()))]
	l.sort()
	c = 0
	count = 0
	now = -1
	for i in range(n):
		if l[i][1] > now:
			now = l[i][1]
			count += 1
		else:
			c = max(c, count)
			count = 1
			now = l[i][1]
	c = max(c, count)
	print(n - c)


for p in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()][:n]
	b = a.copy()
	b.sort()
	c = -1
	for e in range(len(a)):
		m = 0
		g = e
		for j in range(len(a)):
			if g < len(a) and a[j] == b[g]:
				g += 1
				m += 1
		c = max(c, m)
	print(n - c)


import collections
import string

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
				z = max(z, p[0] + 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()


import sys, math, cmath, time, bisect
from collections import deque
start_time = time.time()
tt = 0

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

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

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

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

def solve():
	n = inp()
	arr = inlt()
	M = {}
	brr = []
	for i in range(n):
		brr.append([arr[i], i])
	brr.sort()
	for i in range(n):
		arr[brr[i][1]] = i + 1
	ans = [0] * (n + 1)
	mx = 0
	for i in range(n):
		ans[arr[i]] = ans[arr[i] - 1] + 1
		mx = max(ans[arr[i]], mx)
	return n - mx

def main():
	t = 1
	t = inp()
	for tt in range(t):
		print(solve())

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q
main()


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)


T = int(input())
for _ in range(T):
	n = int(input())
	ls = list(map(int, input().split()))
	cc = {u: i for (i, u) in enumerate(sorted(ls))}
	ls = [cc[u] for u in ls]

	def lcount(i, u):
		cc = 0
		while i >= 0:
			if ls[i] == u:
				cc += 1
				u -= 1
			i -= 1
		return cc

	def rcount(i, u):
		cc = 0
		while i < n:
			if ls[i] == u:
				cc += 1
				u += 1
			i += 1
		return cc
	mn = n
	for (i, u) in enumerate(ls):
		cnt = lcount(i - 1, u - 1) + 1 + rcount(i + 1, u + 1)
		mn = min(mn, n - cnt)
	print(mn)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(range(n), key=lambda x: a[x])
	ans = 0
	c = 1
	for i in range(1, n):
		if b[i] > b[i - 1]:
			c += 1
		else:
			ans = max(ans, c)
			c = 1
	print(n - max(ans, c))


I = lambda : list(map(int, input().split()))

def lis(arr):
	n = len(arr)
	lis = [1] * n
	for i in range(1, n):
		for j in range(0, i):
			if arr[i] == arr[j] + 1 and lis[i] < lis[j] + 1:
				lis[i] = lis[j] + 1
	maximum = 0
	for i in range(n):
		maximum = max(maximum, lis[i])
	return maximum
for tc in range(int(input())):
	(n,) = I()
	l = I()
	ar = l.copy()
	ar.sort()
	f = {}
	for i in range(n):
		f[ar[i]] = i + 1
	for i in range(n):
		l[i] = f[l[i]]
	print(n - lis(l))


import sys

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

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

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

def solve():
	n = mint()
	a = list(mints())
	b = list(enumerate(a))
	b.sort(key=lambda a: a[1])
	c1 = [0] * n
	c = 0
	h = 0
	p = -1
	for (i, v) in b:
		if i > p:
			c += 1
		else:
			c = 1
		h += 1
		c1[i] = h - c
		p = i
	c = 0
	h = 0
	p = -1
	ans = n + n
	for z in range(len(b) - 1, -1, -1):
		(i, v) = b[z]
		if i < p:
			c += 1
		else:
			c = 1
		h += 1
		ans = min(ans, h - c + c1[i])
		p = i
	print(ans)
for i in range(mint()):
	solve()


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a)
	c = {}
	for i in range(n - 1):
		c[b[i + 1]] = b[i]
	c[b[0]] = -1
	li = {}
	for i in a:
		if c[i] in li:
			li[i] = li[c[i]] + 1
		else:
			li[i] = 1
	print(n - max(li.values()))


T = int(input())
while T > 0:
	n = int(input())
	arr = list(map(int, input().split()))
	b = arr.copy()
	b.sort()
	dic = {}
	dp = [0] * (n + 1)
	for i in range(n):
		dic[b[i]] = i + 1
	for i in range(n):
		dp[dic[arr[i]]] = dp[dic[arr[i]] - 1] + 1
	ma = max(dp)
	print(n - ma)
	T -= 1


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import 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 sys import stdin, stdout
t = int(stdin.readline().strip())
for _ in range(t):
	n = int(stdin.readline().strip())
	a = [(int(b), i) for (i, b) in enumerate(stdin.readline().split())]
	a.sort()
	(ans, c) = (0, 1)
	for i in range(1, n):
		if a[i][1] > a[i - 1][1]:
			c += 1
		else:
			ans = max(ans, c)
			c = 1
	else:
		ans = max(ans, c)
	stdout.write('{}\n'.format(n - ans))


from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	lis = list(set(arr))
	lis.sort()
	lis = list(zip(lis, range(0, len(lis))))
	dic = dict(lis)
	inc_sub = defaultdict(int)
	for i in arr:
		ele = dic[i]
		inc_sub[ele] = 1 + max(inc_sub[ele], inc_sub[ele - 1])
	print(n - max(inc_sub.values()))


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = sorted(a)
	d = [0] * (n + 1)
	for i in a:
		d[b.index(i)] = 1 + d[b.index(i) - 1]
	print(n - max(d))


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))

def lis(arr):
	n = len(arr)
	lis = [1] * n
	for i in range(1, n):
		for j in range(0, i):
			if arr[i] == arr[j] + 1 and lis[i] < lis[j] + 1:
				lis[i] = lis[j] + 1
	ma = 0
	for i in range(n):
		ma = max(ma, lis[i])
	return ma
(t,) = I()
for _ in range(t):
	(n,) = I()
	l = I()
	p = list(l)
	k = sorted(l)
	d = {}
	for i in range(n):
		d[k[i]] = i + 1
	for i in range(n):
		l[i] = d[l[i]]
	if k == p:
		print(0)
		continue
	x = lis(l)
	print(n - x)


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)


import sys, math, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
from decimal import Decimal
from fractions import Fraction

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

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
INF = 10 ** 20
mod = 10 ** 9 + 7
global maximum

def _lis(arr, n):
	global maximum
	if n == 1:
		return 1
	maxEndingHere = 1
	for i in range(1, n):
		res = _lis(arr, i)
		if arr[i - 1] < arr[n - 1] and res + 1 > maxEndingHere:
			maxEndingHere = res + 1
	maximum = max(maximum, maxEndingHere)
	return maxEndingHere

def lis(arr):
	global maximum
	n = len(arr)
	maximum = 1
	_lis(arr, n)
	return maximum
for t in range(int(data())):
	n = int(data())
	a = mdata()
	a1 = [(a[i], i) for i in range(n)]
	a1.sort()
	ans = 0
	cnt = 0
	for i in range(n - 1):
		if a1[i + 1][1] - a1[i][1] > 0:
			cnt += 1
		else:
			cnt = 0
		ans = max(ans, cnt)
	ans += 1
	out(n - ans)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	id = list(zip(l, list(range(n))))
	id.sort()
	(val, pos) = zip(*id)
	best = 1
	i = 1
	count = 1
	while True:
		if i >= n:
			break
		if pos[i] > pos[i - 1]:
			count += 1
			best = max(count, best)
		else:
			count = 1
		i += 1
	print(n - best)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(n):
		a[i] = a[i] * n + i
	a.sort()
	p = [0 for _ in range(n)]
	for i in range(n):
		p[a[i] % n] = i
	q = [0 for _ in range(n)]
	for i in range(n):
		q[p[i]] = i
	cnt = 1
	m = 0
	for i in range(1, n):
		if q[i - 1] < q[i]:
			cnt += 1
		else:
			m = max(cnt, m)
			cnt = 1
	m = max(cnt, m)
	print(n - m)


t = int(input())
for i in range(t):
	l = int(input())
	s = list(map(int, input().split()))
	for j in range(l):
		s[j] += j / 100000.0
	sor = sorted(s)
	b = []
	for j in s:
		b.append(sor.index(j))
	dp = [0] * (l + 1)
	for j in range(l):
		dp[b[j]] = 1 + dp[b[j] - 1]
	print(l - max(dp))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	for i in range(n):
		b.append([a[i], i])
	b = sorted(b, key=lambda R: R[0])
	positions = [0] * n
	for i in range(n):
		positions[b[i][1]] = i
	leftmin = []
	rightmin = []
	for i in range(n):
		leftmin.append(0)
		rightmin.append(0)
	for i in range(n - 1):
		for j in range(i + 1):
			if a[j] > a[i + 1]:
				l = positions[i + 1] + 1
				r = n - positions[j]
				for k in range(l - 1, -1, -1):
					if leftmin[k] >= r:
						break
					leftmin[k] = r
				for k in range(r - 1, -1, -1):
					if rightmin[k] >= l:
						break
					rightmin[k] = l
	maximum = n
	for i in range(n):
		maximum = min(maximum, leftmin[i] + i)
		maximum = min(maximum, rightmin[i] + i)
	print(maximum)


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)
		pvr = [(n, 0)]
		for p in reversed(range(n)):
			cur = idx[p]
			stk = [(-1, 0)]
			i = 0
			for x in cur:
				while pvr[i][0] <= x:
					i += 1
				add = (x, pvr[i][1] + 1)
				ans = max(ans, add[1])
				while stk and stk[-1][1] <= add[1]:
					stk.pop()
				stk.append(add)
			stk.append((n, 0))
			pvr = stk
		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()


from sys import stdin, stdout
from math import gcd, sqrt
from collections import deque
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
N = 5 * 10 ** 5 + 7
for _ in range(I()):
	n = I()
	d = {}
	for (i, j) in enumerate(R()):
		d[j] = i
	lst = -1
	mx = cnt = 0
	for i in sorted(d):
		if d[i] > lst:
			cnt += 1
		else:
			cnt = 1
		lst = d[i]
		mx = max(mx, cnt)
	print(n - mx)


from sys import stdin, stdout, setrecursionlimit
for _ in range(int(input())):
	n = int(input())
	a = [[int(i)] for i in input().split()]
	for i in range(n):
		a[i].append(i)
	a = sorted(a)
	ans = 1
	cur = 1
	for i in range(1, n):
		if a[i][1] > a[i - 1][1]:
			cur += 1
		else:
			ans = max(ans, cur)
			cur = 1
		if i == n - 1:
			ans = max(ans, cur)
			cur = 1
	print(n - ans)


def main():
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a)
	d = dict()
	f = dict()
	for i in range(n - 1, -1, -1):
		d[b[i]] = i
	for i in range(n):
		where = d[a[i]]
		if where == 0 or b[where - 1] not in f:
			f[a[i]] = 1
		else:
			f[a[i]] = 1 + f[b[where - 1]]
	print(n - max(f.values()))
tn = int(input())
for _ in range(tn):
	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 factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

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

def RLL():
	return list(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 = 998244353
INF = float('inf')

def main():
	for _ in range(N()):
		n = N()
		arr = RLL()
		sarr = sorted(arr)
		dic = {v: i for (i, v) in enumerate(sarr)}
		dp = [1] * (n + 1)
		for i in range(n):
			for j in range(i - 1, -1, -1):
				now = arr[i]
				ind = dic[now]
				pre = sarr[ind - 1] if ind - 1 >= 0 else -1
				if arr[j] == pre:
					dp[i] = max(dp[i], dp[j] + 1)
					break
		print(n - max(dp))
main()


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

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

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

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

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

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

def main():
	for _ in range(II()):
		n = II()
		aa = LI()
		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 = 1
			if i0 != -1:
				val = dp[i0][1] + 1
			i1 = -1
			if a:
				i1 = last[a - 1]
			if i1 != -1:
				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 = 1
			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 sys
input = sys.stdin.readline
from bisect import bisect_left
for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	S = sorted(set(A))
	m = len(S)
	DP = [0] * m
	for v in A:
		i = bisect_left(S, v)
		DP[i] += 1
		if i:
			DP[i] = max(DP[i], DP[i - 1] + 1)
	print(n - max(DP))


import os
inp = os.read(0, int(10000000.0)).split()
inp_pos = -1

def cin():
	global inp_pos
	inp_pos += 1
	return inp[inp_pos]
from itertools import groupby
from bisect import bisect
T = int(cin())
res = []
while T:
	T -= 1
	n = int(cin())
	a = [[x[1] for x in g] for (k, g) in groupby(sorted([(int(cin()), i) for i in range(n)]), lambda x: x[0])]
	ans = 0
	left = 0
	cur = 0
	m = len(a)
	for right in range(m):
		if right > 0 and a[right][0] < a[right - 1][-1]:
			left = right
			cur = 0
		cur += len(a[right])
		val = cur
		if left > 0:
			val += bisect(a[left - 1], a[left][0])
		if right + 1 < m:
			val += len(a[right + 1]) - bisect(a[right + 1], a[right][-1])
		ans = max(ans, val)
	res.append(str(n - ans).encode())
os.write(1, '\n'.encode().join(res))


from sys import stdin, stdout
from collections import deque
R = lambda : stdin.readline().strip()
RL = lambda : list(map(int, R().split(' ')))
output = lambda x: stdout.write(str(x) + '\n')
for tc in range(int(R())):
	n = int(R())
	a = RL()
	b = a.copy()
	b.sort()
	longest_inc = 0
	for i in range(n):
		length = 0
		j = i
		ptr = 0
		while j < n and ptr < n:
			if b[j] == a[ptr]:
				j += 1
				length += 1
			ptr += 1
		longest_inc = max(longest_inc, length)
	output(n - longest_inc)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [(int(x), i) for (i, x) in enumerate(input().split())]
	a.sort()
	mx = 0
	curl = 0
	prev = -1000
	for (x, i) in a:
		if i > prev:
			curl += 1
		else:
			curl = 1
		prev = i
		if curl > mx:
			mx = curl
	print(n - mx)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	indices = {}
	for i in range(n):
		indices[a[i]] = i
	ordered = sorted(a)
	seq_length = [1] * n
	for i in range(1, n):
		if indices[ordered[i - 1]] < indices[ordered[i]]:
			seq_length[i] = seq_length[i - 1] + 1
	print(n - max(seq_length))


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 = {}
	for i in range(n):
		dic[nums[i]] = i
	nums.sort()
	res = 0
	tmp = 1
	for i in range(1, n):
		if dic[nums[i]] < dic[nums[i - 1]]:
			res = max(res, tmp)
			tmp = 1
		else:
			tmp += 1
	res = max(res, tmp)
	print(n - res)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(list(set(a)))
	max_r = 0
	for i in range(n):
		a[i] = b.index(a[i])
	while a != []:
		r = 0
		last = a[-1]
		for i in range(len(a) - 1, -1, -1):
			if a[i] == last or a[i] + 1 == last:
				r += 1
				last = a[i]
				a.pop(i)
		if r > max_r:
			max_r = r
	print(n - max_r)


test_case = int(input())
for _ in range(test_case):
	input()
	arr = list(map(int, input().split()))
	brr = sorted(arr)
	crr = [0] * (len(arr) + 1)
	for i in arr:
		index = brr.index(i)
		crr[index] = 1 + crr[index - 1]
	print(len(arr) - max(crr))


import sys

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

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

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

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

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

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

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

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

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7

def compress(S):
	(zipped, unzipped) = ({}, {})
	for (i, a) in enumerate(sorted(S)):
		zipped[a] = i
		unzipped[i] = a
	return (zipped, unzipped)
for _ in range(INT()):
	N = INT()
	A = LIST()
	(zipped, _) = compress(A)
	for i in range(N):
		A[i] = zipped[A[i]]
	B = [0] * N
	for (i, a) in enumerate(A):
		B[a] = i
	mx = cnt = 1
	for i in range(N - 1):
		if B[i] < B[i + 1]:
			cnt += 1
		else:
			cnt = 1
		mx = max(mx, cnt)
	print(N - mx)


from itertools import islice
for t in range(int(input())):
	n = int(input())
	aa = list(map(int, input().split(' ')))
	asort = sorted(aa)
	ls = [None] * n
	for (i, a) in enumerate(asort):
		ai = aa.index(a)
		l = 1
		if i >= 1:
			pi = aa.index(asort[i - 1])
			if pi < ai:
				l = ls[pi] + 1
		ls[ai] = l
	print(n - max(ls))


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
from math import inf
from bisect import bisect_left

def get_lis(a):
	dp = [0] * len(a)
	aux = [inf] * (len(a) + 1)
	aux[0] = -inf
	high = 0
	for i in range(len(a)):
		dp[i] = bisect_left(aux, a[i])
		aux[dp[i]] = min(aux[dp[i]], a[i])
		high = max(high, dp[i])
	return high

def get_subsequence(a, k):
	if k > len(a):
		return None
	dp = [0] * len(a)
	aux = [inf] * (k + 1)
	aux[0] = -inf
	high = 0
	for i in range(len(a)):
		dp[i] = bisect_left(aux, a[i])
		aux[dp[i]] = min(aux[dp[i]], a[i])
		high = max(high, dp[i])
		if high == k:
			return aux[1:]
	return None
for _ in range(int(input()) if True else 1):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	sa = sorted(a) + [10 ** 18]
	for i in range(n):
		count = 1
		value = sa[i]
		cur = i + 1
		for j in range(a.index(value) + 1, n):
			if a[j] == sa[cur]:
				count += 1
				cur += 1
		ans = max(ans, count)
	print(n - ans)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	narr = dict()
	for i in range(n):
		narr[arr[i]] = i
	arr.sort()
	ct = ans = 0
	for i in range(n):
		if i > 0 and narr[arr[i]] < narr[arr[i - 1]]:
			ct = 0
		ct += 1
		ans = max(ct, ans)
	print(n - ans)


t = int(input())
for you in range(t):
	n = int(input())
	l = input().split()
	li = [int(i) for i in l]
	z = list(li)
	z.sort()
	hashi = dict()
	for i in range(n):
		hashi[z[i]] = i + 1
	for i in range(n):
		li[i] = hashi[li[i]]
	hashi = dict()
	dp = [0 for i in range(n)]
	for i in range(n):
		if li[i] - 1 in hashi:
			dp[i] = hashi[li[i] - 1] + 1
			hashi[li[i]] = dp[i]
		else:
			dp[i] = 1
			hashi[li[i]] = 1
	z = max(dp)
	print(n - z)


def maxSubsequenceSubstring(x, y, n, m):
	dp = [[0 for i in range(n + 1)] for i in range(n + 1)]
	for i in range(1, m + 1):
		for j in range(1, n + 1):
			if x[j - 1] == y[i - 1]:
				dp[i][j] = 1 + dp[i - 1][j - 1]
			else:
				dp[i][j] = dp[i][j - 1]
	ans = 0
	for i in range(1, m + 1):
		ans = max(ans, dp[i][n])
	return ans
t = int(input())
while t:
	t -= 1
	n = int(input())
	l = list(map(int, input().split()))
	q = sorted(l)
	print(n - maxSubsequenceSubstring(l, q, len(l), len(q)))


import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def solve(N, A):
	B = list(sorted(set(A)))
	B.sort()
	to = {v: i for (i, v) in enumerate(B)}
	A = [to[v] for v in A]
	dp = [1 for i in range(N + 1)]
	vi = [-1 for _ in range(N + 1)]
	for (i, v) in enumerate(A):
		dp[i] = max(dp[i], (dp[vi[v - 1]] if v - 1 >= 0 and vi[v - 1] >= 0 else 0) + 1)
		vi[v] = i
	return N - max(dp)
T = int(input())
ans = []
for ti in range(T):
	N = int(input())
	A = [int(x) for x in input().split()]
	ans.append(solve(N, A))
print('\n'.join(map(str, 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_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
inp = os.read(0, int(10000000.0)).split()
inp_pos = -1

def cin():
	global inp_pos
	inp_pos += 1
	return inp[inp_pos]
from bisect import bisect
T = int(cin())
res = []
while T:
	T -= 1
	n = int(cin())
	a = sorted([(int(cin()), i) for i in range(n)])
	before = [0 for i in range(n)]
	after = [0 for i in range(n)]
	pre = [-1 for i in range(n)]
	start = 0
	for i in range(n):
		if i == 0:
			before[a[i][1]] = 1
		elif a[i][0] != a[i - 1][0]:
			before[a[i][1]] = 1 + bisect(a, (a[i - 1][0], a[i][1]), start, i) - start
			start = i
		if i > 0:
			pre[a[i][1]] = a[i - 1][1]
	last = n
	for i in range(n - 1, -1, -1):
		if i == n - 1:
			after[a[i][1]] = 0
		elif a[i][0] != a[i + 1][0]:
			after[a[i][1]] = last - bisect(a, (a[i + 1][0], a[i][1]), i + 1, last)
			last = i + 1
	ans = 0
	dp = [0 for i in range(n + 1)]
	for i in range(n):
		dp[i] = max(before[i], dp[pre[i]] + 1)
		ans = max(ans, dp[i] + after[i])
	res.append(str(n - ans).encode())
os.write(1, '\n'.encode().join(res))


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
	for i in range(n):
		aOrder[p[i][1]] = i
	maxSubseq = []
	for i in range(n):
		maxSubseqcur = 0
		for j in range(i):
			if aOrder[i] - aOrder[j] == 1 and maxSubseqcur < maxSubseq[j]:
				maxSubseqcur = maxSubseq[j]
		maxSubseq.append(maxSubseqcur + 1)
	print(n - max(maxSubseq))


import sys
input = sys.stdin.readline
import bisect
t = int(input())
for tests in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	compression_dict = {a: ind for (ind, a) in enumerate(sorted(set(A)))}
	A = [compression_dict[a] for a in A]
	Q = [0] * n
	for i in range(n):
		Q[A[i]] = i
	count = 1
	Ans = 0
	for i in range(1, n):
		if Q[i] > Q[i - 1]:
			count += 1
		else:
			Ans = max(count, Ans)
			count = 1
	Ans = max(count, Ans)
	print(n - Ans)


production = True
import sys, math, collections

def input(input_format=0, multi=0):
	if multi > 0:
		return [input(input_format) for i in range(multi)]
	else:
		next_line = sys.stdin.readline()[:-1]
		if input_format >= 10:
			use_list = False
			input_format = int(str(input_format)[-1])
		else:
			use_list = True
		if input_format == 0:
			formatted_input = [next_line]
		elif input_format == 1:
			formatted_input = list(map(int, next_line.split()))
		elif input_format == 2:
			formatted_input = list(map(float, next_line.split()))
		elif input_format == 3:
			formatted_input = list(next_line)
		elif input_format == 4:
			formatted_input = list(map(int, list(next_line)))
		elif input_format == 5:
			formatted_input = next_line.split()
		else:
			formatted_input = [next_line]
		return formatted_input if use_list else formatted_input[0]

def out(output_line, output_format=0, newline=True):
	formatted_output = ''
	if output_format == 0:
		formatted_output = str(output_line)
	elif output_format == 1:
		formatted_output = ' '.join(map(str, output_line))
	elif output_format == 2:
		formatted_output = '\n'.join(map(str, output_line))
	print(formatted_output, end='\n' if newline else '')

def log(*args):
	if not production:
		print('$$$', end='')
		print(*args)
enu = enumerate
ter = lambda a, b, c: b if a else c

def mapl(iterable, format=0):
	if format == 0:
		return list(map(int, iterable))
	elif format == 1:
		return list(map(str, iterable))
	elif format == 2:
		return list(map(list, iterable))

def solve():
	n = input(11)
	a = input(1)
	b = sorted(a) + [-1]
	m = 0
	for i in range(n):
		c = b.index(a[i])
		t = 1
		for j in range(i, n):
			if a[j] == b[c + 1]:
				t += 1
				c += 1
		m = max(t, m)
	out(n - m)
	return
for i in range(input(11)):
	solve()


import sys

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]
for p in range(ii()):
	n = ii()
	a = li()
	b = a.copy()
	b.sort()
	c = -1
	for e in range(len(a)):
		m = 0
		g = e
		for j in range(len(a)):
			if g < len(a) and a[j] == b[g]:
				g += 1
				m += 1
		c = max(c, m)
	print(n - c)


import sys
input = sys.stdin.readline
from collections import *

def compress(l):
	l = list(set(l))
	l.sort()
	idx = defaultdict(int)
	for i in range(len(l)):
		idx[l[i]] = i
	return idx
t = int(input())
for _ in range(t):
	N = int(input())
	a = list(map(int, input().split()))
	m = compress(a)
	for i in range(N):
		a[i] = m[a[i]] + 1
	idx = defaultdict(int)
	for i in range(N):
		idx[a[i]] = i
	dp = [0] * N
	for i in range(N):
		if a[i] == 1:
			dp[i] = 1
		else:
			dp[i] = dp[idx[a[i] - 1]] + 1
	print(N - max(dp))


tt = int(input())
for loop in range(tt):
	n = int(input())
	a = list(map(int, input().split()))
	ai = []
	for i in range(n):
		ai.append((a[i], i))
	ai.sort()
	ind = 0
	b = [0] * n
	non = [0] * (n + 1)
	for i in range(n):
		if i != 0 and ai[i][0] != ai[i - 1][0]:
			ind += 1
		b[ai[i][1]] = ind
		non[ind] += 1
	dp = [0] * (n + 1)
	for i in range(n):
		dp[b[i]] += max(dp[b[i]], dp[b[i] - 1] + 1)
	print(n - max(dp))


import sys
input = sys.stdin.readline
import bisect
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = sorted(a)
	d = [0] * (n + 1)
	for i in a:
		d[b.index(i)] = 1 + max(d[b.index(i)], d[b.index(i) - 1])
	print(n - max(d))


for p in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()][:n]
	b = a.copy()
	b.sort()
	c = []
	e = 0
	while True:
		x = b.index(a[e])
		m = 1
		for j in range(e, len(a)):
			if x <= len(a) - 2:
				if a[j] == b[x + 1]:
					x += 1
					m += 1
		c.append(m)
		e += 1
		if e == len(a):
			break
	print(n - max(c))


import sys, math, cmath, time
start_time = time.time()

def solve():
	n = inp()
	a = inlt()
	q = [[a[i], i] for i in range(len(a))]
	w = [1] * len(a) + [0]
	q.sort()
	qw = [q[i][1] for i in range(len(a))] + [-1]
	qq = 1
	for i in range(len(a) - 1, -1, -1):
		if qw[i] < qw[i + 1]:
			w[i] = w[i + 1] + 1
		qq = max(qq, w[i])
	print(len(a) - qq)

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(t):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

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

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

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

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

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


from sys import stdin

def bsearch(lis, idx, val):
	l = 0
	h = idx
	while l <= h:
		mid = (l + h) // 2
		if lis[mid] == val:
			return mid
		if lis[mid] > val:
			h = mid - 1
		else:
			l = mid + 1

def res(arr):
	lis_f = sorted(arr)
	_arr = [0 for i in range(len(arr))]
	for i in range(len(arr)):
		_arr[bsearch(lis_f, len(arr) - 1, arr[i])] = i
	c = 1
	p = 0
	for j in range(1, len(arr)):
		if _arr[j] > _arr[j - 1]:
			c += 1
		elif c > p:
			p = c
			c = 1
		else:
			c = 1
	if c > p:
		p = c
	print(len(arr) - p)
k = int(stdin.readline())
while k:
	stdin.readline()
	res(list(map(int, stdin.readline().split())))
	k -= 1


from sys import stdin

def search(lis, idx, val):
	low = 0
	high = idx
	while low <= high:
		mid = (low + high) // 2
		if lis[mid] == val:
			return mid
		if lis[mid] > val:
			high = mid - 1
		else:
			low = mid + 1

def ans(arr):
	lis_f = sorted(arr)
	ans_arr = [0] * len(arr)
	for i in range(len(arr)):
		ans_arr[search(lis_f, len(arr) - 1, arr[i])] = i
	c = 1
	p = 0
	for j in range(1, len(arr)):
		if ans_arr[j] > ans_arr[j - 1]:
			c += 1
		elif c > p:
			p = c
			c = 1
		else:
			c = 1
	if c > p:
		p = c
	print(len(arr) - p)
for i in range(int(stdin.readline())):
	stdin.readline()
	ans(list(map(int, stdin.readline().split())))


import sys

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

def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		b = [[a[k], k] for k in range(n)]
		b = sorted(b)
		c = [b[k][1] for k in range(n)]
		c = [-1] + c + [100000]
		t = 0
		ans = 0
		for k in range(1, n + 1):
			if c[k - 1] < c[k]:
				t += 1
			else:
				t = 1
			ans = max(ans, t)
		print(n - ans)
main()


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
from functools import *
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')

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

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

def N():
	return int(input())
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
mod = 10 ** 9 + 7
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	fact(x, mod)
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa.reverse()

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def floorsum(a, b, c, n):
	if a == 0:
		return b // c * (n + 1)
	if a >= c or b >= c:
		return floorsum(a % c, b % c, c, n) + b // c * (n + 1) + a // c * n * (n + 1) // 2
	m = (a * n + b) // c
	return n * m - floorsum(c, c - b - 1, a, m - 1)

def lowbit(n):
	return n & -n

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] > self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return (flag, prime)

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		seen.add(u)
		for (v, w) in graph[u]:
			if v not in d or d[v] > d[u] + w:
				d[v] = d[u] + w
				heappush(heap, (d[v], v))
	return d

def GP(it):
	return [[ch, len(list(g))] for (ch, g) in groupby(it)]

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

def lis(nums):
	res = []
	for k in nums:
		i = bisect.bisect_left(res, k)
		if i == len(res):
			res.append(k)
		else:
			res[i] = k
	return len(res)

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None

def nb(i, j):
	for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j - 1], [i, j + 1]]:
		if 0 <= ni < n and 0 <= nj < m:
			yield (ni, nj)

def topo(n):
	q = deque()
	res = []
	for i in range(1, n + 1):
		if ind[i] == 0:
			q.append(i)
			res.append(i)
	while q:
		u = q.popleft()
		for v in g[u]:
			ind[v] -= 1
			if ind[v] == 0:
				q.append(v)
				res.append(v)
	return res

@bootstrap
def gdfs(r, p):
	if len(g[r]) == 1 and p != -1:
		yield None
	for ch in g[r]:
		if ch != p:
			yield gdfs(ch, r)
	yield None

@bootstrap
def dfs(r):
	vis[r] = 1
	ans[r - 1] = val[r]
	for ch in g[r]:
		if d[ch] > d[r]:
			yield dfs(ch)
			ans[r - 1] = min(ans[r - 1], ans[ch - 1])
	yield None

def f(x, g):
	ans = 0
	for ch in res:
		ans += c[ch] // x
	return ans >= g
t = N()
for i in range(t):
	n = N()
	a = RLL()
	d = {x: i for (i, x) in enumerate(a)}
	res = sorted(a)
	b = [0] * (n - 1)
	for i in range(n - 1):
		if d[res[i]] < d[res[i + 1]]:
			b[i] = 1
	g = GP(b)
	ans = 0
	for (ch, l) in g:
		if ch == 1:
			ans = max(ans, l)
	ans = n - ans - 1
	print(ans)


import sys
import math

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

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

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

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	n = II()
	arr = LI()
	lis = [1] * n
	a = sorted(arr)
	d = {}
	for i in range(1, n):
		d[a[i]] = a[i - 1]
	for i in range(1, n):
		for j in range(0, i):
			if arr[i] != a[0] and d[arr[i]] == arr[j] and (lis[i] < lis[j] + 1):
				lis[i] = lis[j] + 1
	maximum = 0
	for i in range(n):
		maximum = max(maximum, lis[i])
	print(n - maximum)


import sys
input = sys.stdin.readline

def main():
	t = int(input())
	for _ in range(t):
		N = int(input())
		A = [int(x) for x in input().split()]
		Asort = sorted(A)
		dp = [0] * (N + 1)
		dic = {}
		for (i, a) in enumerate(Asort):
			dic[a] = i + 1
		for a in A:
			dp[dic[a]] = dp[dic[a] - 1] + 1
		print(N - max(dp))
main()


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


import heapq
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	h = []
	for i in range(n):
		heapq.heappush(h, (a[i], i + 1))
	j = 0
	(c, m) = (0, 0)
	while h:
		(ai, i) = heapq.heappop(h)
		if j < i:
			c += 1
		else:
			c = 1
		j = i
		m = max(m, c)
	ans = n - m
	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')

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
input = sys.stdin.readline
for nt in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a)
	l = {}
	for i in range(n):
		l[b[i]] = i
	if a == b:
		print(0)
		continue
	dp = [0] * (n + 1)
	for i in range(n):
		dp[l[a[i]]] = 1 + dp[l[a[i]] - 1]
	print(n - max(dp))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for x in sorted(a):
		d[x] = len(d)
	b = [d[x] for x in a]
	l = [0] * n
	r = [0] * n
	for x in b:
		l[x] = 1
		if x - 1 >= 0:
			l[x] += l[x - 1]
	for x in b[::-1]:
		r[x] = 1
		if x + 1 < n:
			r[x] += r[x + 1]
	print(n - max([x + y - 1 for (x, y) in zip(l, r)]))


def remainderSorted(x, n, a, b):
	mn = b[x[0]]
	mx = b[x[1]]
	prev = None
	for e in a:
		if e >= mn and e <= mx:
			if prev is not None and prev > e:
				return False
			prev = e
	return True

def count(n, a):
	mincnt = 0
	for i in range(1, n):
		if a[i - 1] > a[i]:
			mincnt += 1
	b = sorted(a)
	seen = {(0, -1): 1}
	list = [(0, -1)]
	while True:
		x = list.pop(0)
		cnt = x[0] - x[1] - 1
		if cnt >= mincnt and remainderSorted(x, n, a, b):
			return cnt
		else:
			xnew = (x[0] + 1, x[1])
			if xnew not in seen:
				list.append(xnew)
				seen[xnew] = 1
			xnew = (x[0], x[1] - 1)
			if xnew not in seen:
				list.append(xnew)
				seen[xnew] = 1

def count2(n, a):
	b = sorted(a)
	h = {a[i]: i for i in range(n)}
	ms = [int(h[b[i]] < h[b[i - 1]]) for i in range(1, n)]
	gap = 0
	maxgap = 0
	for m in ms:
		if m == 0:
			gap += 1
			maxgap = max(gap, maxgap)
		else:
			gap = 0
	return n - maxgap - 1
t = int(input().strip())
for _ in range(t):
	n = int(input().strip())
	a = list(map(int, input().strip().split()))
	print(count2(n, a))


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


import io, os
from enum import unique
from heapq import *

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

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

def Solve():
	n = ri()
	a = rl()
	b = sorted(a)
	mp = dict()
	cnt = 0
	for x in b:
		if x not in mp:
			mp[x] = cnt
			cnt += 1
	for i in range(n):
		a[i] = mp[a[i]]
	dp = [1] * n
	pos = [0] * n
	for i in range(n):
		pos[a[i]] = i
	for i in range(1, n):
		if a[i] - 1 >= 0 and pos[a[i] - 1] < i:
			dp[i] = dp[pos[a[i] - 1]] + 1
	print(n - max(dp))
T = ri()
while T:
	T -= 1
	Solve()


from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	brr = arr[:]
	ind = defaultdict(int)
	for i in range(n):
		ind[arr[i]] = i
	brr.sort()
	ans = [0 for i in range(n)]
	for i in range(n):
		start_ind = ind[brr[i]]
		k = 1
		count = 1
		if i + 1 < n:
			cnt = brr[i + k]
			for j in range(start_ind + 1, n):
				if arr[j] == cnt:
					k += 1
					count += 1
					if i + k < n:
						cnt = brr[i + k]
					else:
						break
		ans[i] = count
	print(n - max(ans))


from collections import defaultdict

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		A = list(map(int, input().split()))
		A = [a - 1 for a in A]
		SET = set([])
		for a in A:
			SET.add(a)
		dic = defaultdict(int)
		LIST = list(SET)
		LIST.sort()
		num = 0
		for a in LIST:
			dic[a] = num
			num += 1
		B = [-1] * n
		for (i, a) in enumerate(A):
			B[dic[a]] = i
		mx_seq = 1
		pre = B[0]
		temp = 1
		for i in range(1, n):
			if B[i] > pre:
				temp += 1
				pre = B[i]
				mx_seq = max(mx_seq, temp)
			else:
				mx_seq = max(mx_seq, temp)
				pre = B[i]
				temp = 1
		print(n - mx_seq)
main()


import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
from math import *
import copy
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

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

def fi():
	return int(input())

def si():
	return list(input().rstrip())

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

def gh():
	sys.stdout.flush()

def bo(i):
	return ord(i) - ord('a')
from copy import *
from bisect import *
from itertools import permutations
tt = fi()
while tt > 0:
	tt -= 1
	n = fi()
	a = li()
	b = sorted(set(a))
	d = {}
	for i in range(len(b)):
		d[b[i]] = i
	for i in range(n):
		a[i] = d[a[i]]
	maxi = 0
	d = [1 for i in range(n + 1)]
	for i in range(n):
		for j in range(i):
			if a[j] == a[i] - 1 or a[j] == a[i]:
				d[i] = max(d[i], d[j] + 1)
	print(n - max(d))


import os
import sys
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		n = int(input())
		a = [int(x) for x in input().split()]
		b = [x for x in a]
		b.sort()
		ans = n
		for i in range(len(a)):
			cnt = 0
			j = i
			for y in a:
				if j < len(b) and y == b[j]:
					j += 1
					cnt += 1
				ans = min(ans, n - cnt)
		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
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 dic.values():
		res = max(len(a), res)
	print(n - res)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	indexOf = {}
	for i in range(n):
		indexOf[a[i]] = i
	values = sorted(list(set(a)))
	visited = [False for _ in range(n)]
	ng = [n for _ in range(n)]
	for i in range(n):
		lo = 0
		hi = len(values) - 1
		while lo < hi:
			mid = (lo + hi) // 2
			if values[mid] < a[i]:
				lo = mid + 1
			else:
				hi = mid
		if lo != len(values) - 1:
			ng[i] = indexOf[values[lo + 1]]
	ans = n
	for i in range(n):
		if visited[i]:
			continue
		tempAns = n
		at = i
		while at != n:
			visited[at] = True
			tempAns -= 1
			if ng[at] > at:
				at = ng[at]
			else:
				at = n
		ans = min(ans, tempAns)
	print(ans)


def flyingsort(L):
	d = {}
	for i in range(len(L)):
		d[L[i]] = i
	L.sort()
	prev = -1
	run = 0
	maxRun = -1
	for i in L:
		if d[i] > prev:
			run += 1
		else:
			run = 1
		maxRun = max(maxRun, run)
		prev = d[i]
	return len(L) - maxRun
T = int(input())
for i in range(T):
	N = int(input())
	L = list(map(int, input().split(' ')))
	print(flyingsort(L))