Let's denote a $k$-step ladder as the following structure: exactly $k + 2$ wooden planks, of which

  two planks of length at least $k+1$ — the base of the ladder;  $k$ planks of length at least $1$ — the steps of the ladder; 

Note that neither the base planks, nor the steps planks are required to be equal.

For example, ladders $1$ and $3$ are correct $2$-step ladders and ladder $2$ is a correct $1$-step ladder. On the first picture the lengths of planks are $[3, 3]$ for the base and $[1]$ for the step. On the second picture lengths are $[3, 3]$ for the base and $[2]$ for the step. On the third picture lengths are $[3, 4]$ for the base and $[2, 3]$ for the steps. 

 $H - 1 =$ 

You have $n$ planks. The length of the $i$-th planks is $a_i$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised "ladder" from the planks.

The question is: what is the maximum number $k$ such that you can choose some subset of the given planks and assemble a $k$-step ladder using them?


-----Input-----

The first line contains a single integer $T$ ($1 \le T \le 100$) — the number of queries. The queries are independent.

Each query consists of two lines. The first line contains a single integer $n$ ($2 \le n \le 10^5$) — the number of planks you have.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^5$) — the lengths of the corresponding planks.

It's guaranteed that the total number of planks from all queries doesn't exceed $10^5$.


-----Output-----

Print $T$ integers — one per query. The $i$-th integer is the maximum number $k$, such that you can choose some subset of the planks given in the $i$-th query and assemble a $k$-step ladder using them.

Print $0$ if you can't make even $1$-step ladder from the given set of planks.


-----Example-----
Input
4
4
1 3 1 3
3
3 3 2
5
2 3 3 4 2
3
1 1 2

Output
2
1
2
0



-----Note-----

Examples for the queries $1-3$ are shown at the image in the legend section.

The Russian meme to express the quality of the ladders:

 [Image]

Source: codeforces | Difficulty: EASY
Tags: Sorting

Mathematics

Greedy algorithms


Solutions:
for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	l.sort()
	a = l[-1]
	b = l[-2]
	if a <= 1 or b <= 1:
		print(0)
	else:
		print(min(b - 1, n - 2))


T = int(input())
for _ in range(T):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	l = len(arr)
	if l > 2:
		step = arr[l - 2]
		print(min(step - 1, l - 2))
	else:
		print(0)


queries = int(input())
result = []
for query in range(queries):
	boards = input()
	lengths = list(map(int, input().split()))
	if boards == 2:
		result.append(0)
		continue
	lengths.sort(reverse=True)
	if lengths[1] <= len(lengths) - 2:
		result.append(lengths[1] - 1)
	else:
		result.append(len(lengths) - 2)
for num in result:
	print(num)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	a.sort()
	ans = 0
	if n > 2:
		ans = min(min(a[-1], a[-2]) - 1, n - 2)
	print(ans)


t = input()
for _ in range(int(t)):
	c = input()
	ss = map(int, input().split(' '))
	s = sorted(ss)
	a = s.pop()
	b = s.pop()
	m = min(a, b)
	print(min(m - 1, len(s)))


ll = lambda : list(map(int, input().split()))
testcases = 1
testcases = int(input())
for testcase in range(testcases):
	[n] = ll()
	a = ll()
	a.sort()
	print(min(n - 2, a[n - 2] - 1))


n = int(input())
for i in range(n):
	q = int(input())
	p = input()
	p = p.split(' ')
	p = [int(a) for a in p]
	p.sort(reverse=True)
	minimum = min(p[0], p[1])
	print(min(minimum - 1, q - 2))


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	k = n - 2
	arr.sort(reverse=True)
	if n == 2:
		ans = 0
	elif arr[1] == 1:
		ans = 0
	else:
		ans = min(arr[1] - 1, k)
	print(ans)


for t in range(int(input().strip())):
	n = int(input())
	plks = sorted(list(map(int, input().strip().split())), reverse=True)
	if n < 3:
		print(0)
		continue
	else:
		print(max(min(plks[1] - 1, n - 2), 0))


t = int(input())
for i in range(t):
	a = int(input())
	b = list(map(int, input().split()))
	b.sort()
	maxK = b[-2] - 1
	currentK = len(b) - 2
	if currentK > maxK:
		currentK = maxK
	print(currentK)


k = int(input())
for ll in range(k):
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort()
	n -= 2
	m = a[n] - 1
	l = min(n, m)
	print(l)


T = int(input())
for i in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	print(min(len(a) - 2, max(a[-2] - 1, 0)))


x = int(input())
for _ in range(x):
	l = int(input())
	p = sorted(map(int, input().split()))
	print(min(p[-2] - 1, max(0, l - 2)))


from sys import stdin
T = int(stdin.readline())
for i in range(0, T):
	n = int(stdin.readline())
	A = sorted([int(i) for i in stdin.readline().split(' ')])
	if len(A) < 3:
		print(0)
		continue
	print(min(len(A) - 2, A[-2] - 1))


for i in range(int(input())):
	n = int(input())
	planks = list(map(int, input().split()))
	planks.sort()
	print(min(len(planks) - 2, planks[-2] - 1))


t = int(input())
for _ in range(t):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	x = a[-1]
	a = a[:-1]
	y = a[-1]
	a = a[:-1]
	n = len(a)
	z = min(x, y) - 1
	print(min(z, n))


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	if n < 3 or a[1] < 2:
		print(0)
	elif a[1] - 1 <= n - 2:
		print(a[1] - 1)
	else:
		print(n - 2)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split(' ')]
	if n <= 2:
		print(0)
		continue
	max = -1
	smax = -1
	for i in a:
		if i > max:
			smax = max
			max = i
			continue
		if i > smax and i <= max:
			smax = i
	r = min(smax - 1, len(a) - 2)
	print(r)


n = int(input())
for i in range(n):
	l = int(input())
	a = list(map(int, input().split()))
	a = list(sorted(a))
	print(min(a[-2] - 1, l - 2))


t = int(input())
for z in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	print(min(arr[-2] - 1, len(arr[:-2])))


t = int(input())
for test in range(t):
	n = int(input())
	madeiras = list(map(int, input().split()))
	madeiras.sort()
	resposta = min(n - 2, madeiras[-2] - 1)
	print(resposta)


for _ in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	arr.sort()
	print(min(arr[n - 2] - 1, n - 2))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	s = sum((x >= 1 for x in a[:-2]))
	print(min(s, a[-2] - 1))


def answer():
	n = int(input())
	a = sorted(map(int, input().split(' ')), reverse=True)
	k1 = min(a[0], a[1]) - 1
	k2 = n - 2
	out = min(k1, k2)
	return out
t = int(input())
for i in range(t):
	out = answer()
	print(out)


for _ in range(int(input())):
	x = int(input()) - 2
	l = sorted(list(map(int, input().split())), reverse=True)
	bool = False
	kplus_count = 0
	while x >= 1:
		for num in l:
			if num >= x + 1:
				kplus_count += 1
				if kplus_count >= 2:
					print(x)
					bool = True
					break
			elif num < x + 1:
				break
		if bool:
			break
		else:
			x -= 1
			kplus_count = 0
	else:
		print(0)


t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	seclast = arr[-2] - 1
	if n < 3:
		print(0)
	elif len(arr) - 2 < seclast:
		print(len(arr) - 2)
	else:
		print(seclast)


for _ in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	print(min(a[-2] - 1, n - 2))


t = int(input())
for l in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	a = arr[-2]
	print(min(a - 1, n - 2))


from sys import stdin

def max1_2(list):
	max = 0
	sec_max = 0
	for e in list:
		if e > max:
			sec_max = max
			max = e
		elif e > sec_max:
			sec_max = e
	return (max, sec_max)
n_q = int(stdin.readline())
out = list()
for i in range(n_q):
	n_planks = int(stdin.readline())
	planks = [int(u) for u in stdin.readline().split()]
	(base1, base2) = max1_2(planks)
	min_len = min(planks)
	out.append(min(len(planks) - 2, base2 - 1))
for e in out:
	print(e)


for _ in range(int(input())):
	N = int(input())
	A = list(map(int, input().strip().split()))
	x = max(A)
	A.remove(x)
	y = max(A)
	A.remove(y)
	ans = N - 2
	if ans > y - 1:
		ans = y - 1
	print(ans)


import math
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
M = 10 ** 9 + 7

def isprime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def Freq(l):
	f = {}
	for i in l:
		if i in f:
			f[i] += 1
		else:
			f[i] = 1
	return f
inp = lambda : int(stdin.readline())
sip = lambda : stdin.readline()
mulip = lambda : map(int, stdin.readline().split())
lst = lambda : list(map(int, stdin.readline().split()))
slst = lambda : list(sip())
for _ in range(inp()):
	n = inp()
	A = lst()
	A = sorted(A)
	if len(A) == 2:
		print(0)
	else:
		step_req = A[-2] - 1
		avail_steps = len(A) - 2
		print(min(step_req, avail_steps))


import sys
input = sys.stdin.readline
n = int(input())
for i in range(n):
	t = int(input())
	b = sorted(list(map(int, input().split())), reverse=True)
	if len(b) == 2:
		print(0)
	else:
		p = b[1] - 1
		q = min(p, t - 2)
		print(q)


import math
import sys
import collections

def getdict(n):
	d = {}
	if type(n) is list:
		for i in n:
			if i in d:
				d[i] += 1
			else:
				d[i] = 1
	else:
		for i in range(n):
			t = ii()
			if t in d:
				d[t] += 1
			else:
				d[t] = 1
	return d

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

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

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

def li():
	return list(map(int, input().split()))
t = ii()
for i in range(t):
	n = ii()
	d = sorted(li())
	print(min(d[-2] - 1, n - 2))


quoties = int(input())
resultado = []
segundo_maximo = 0
while quoties != 0:
	n = int(input())
	length = list(map(int, input().split(' ')))
	steps = n - 2
	length.sort(reverse=False)
	segundo_maximo = length[-2] - 1
	resultado.append(min(segundo_maximo, steps))
	quoties -= 1
for contador in resultado:
	print(contador)


def get_max_steps(l):
	l.sort()
	k = 0
	lower_base = min(l[-1], l[-2])
	for i in range(len(l) - 2):
		if k + 1 < lower_base:
			k += 1
	return k
n = int(input())
for _ in range(n):
	t = input()
	lengths = list(map(int, input().split()))
	print(get_max_steps(lengths))


t = int(input())
i = 0
while i < t:
	n = input()
	a = list(map(int, input().split()))
	j = 0
	while j < 2:
		max = [0, 0]
		for l in a:
			if l > max[j]:
				max[j] = l
		a.pop(a.index(max[j]))
		j += 1
	if len(a) > max[1] - 1:
		print(max[1] - 1)
	else:
		print(len(a))
	i += 1


p = int(input())
for q in range(p):
	n = int(input())
	l = sorted(list(map(int, input().split())))
	print(min(l[-2] - 1, n - 2))


T = int(input())
results = []
for i in range(0, T):
	t_loop = int(input())
	stair_array = [int(x) for x in input().split(' ')]
	first_max_length = 0
	second_max_length = 0
	for j in range(0, t_loop):
		if stair_array[j] > first_max_length:
			second_max_length = first_max_length
			first_max_length = stair_array[j]
		elif stair_array[j] > second_max_length:
			second_max_length = stair_array[j]
	if t_loop - 2 >= second_max_length:
		results.append(second_max_length - 1)
	else:
		results.append(t_loop - 2)
for r in results:
	print(r)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	x = min(a[-1], a[-2])
	a.pop()
	a.pop()
	i = 0
	while a and i < x - 1 and (i < n - 2):
		i += 1
	print(min(i, x))


t = int(input())
for _ in range(0, t):
	n = int(input())
	ss = sorted([int(i) for i in input().split()])
	kk = ss[-2]
	possible = kk - 1
	steps_left = n - 2
	print(min(possible, steps_left))


t = int(input())
for i in range(t):
	n = int(input())
	ladder = list(map(int, input().split()))
	ladder.sort()
	print(min(n - 2, ladder[-2] - 1))


q = int(input())
for n in range(q):
	N = int(input())
	e = input().split(' ')
	for i in range(N):
		e[i] = int(e[i])
	e.sort()
	napr2 = e[N - 1]
	napr1 = e[N - 2]
	if napr2 > 1:
		print(min(N - 2, napr1 - 1))
	else:
		print(0)


for _ in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	a.sort()
	print(min(n - 2, a[-2] - 1))


def main():
	t = int(input())
	while t > 0:
		t -= 1
		n = int(input())
		line = input().split()
		v = [int(x) for x in line]
		v.sort()
		mx = v[n - 2]
		ans = min(mx - 1, n - 2)
		print(ans)
main()


nq = int(input())
for i in range(nq):
	p = int(input())
	pl = list(map(int, input().split()))
	pl.sort()
	if p >= 3:
		if p - 2 < min(int(pl[-1]), int(pl[-2])):
			print(p - 2)
		else:
			print(min(int(pl[-1]), int(pl[-2])) - 1)
	else:
		print(0)


from sys import stdin
input = stdin.readline
T = int(input())
for _ in range(T):
	n = int(input())
	a = [int(i) for i in input().split()]
	if n < 3:
		print(0)
	else:
		a = sorted(a, reverse=True)
		print(min([a[1] - 1, n - 2]))


t = int(input())
for test in range(t):
	n = int(input())
	planks = list(map(int, input().split()))
	planks.sort()
	ans = min(n - 2, planks[n - 2] - 1)
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().strip().split()))
	arr = sorted(arr, reverse=True)
	print(min(arr[1] - 1, n - 2))


def max_ladder(A, N):
	Max_1 = 1
	Max_2 = 1
	for i in A:
		if i >= Max_1:
			Max_2 = Max_1
			Max_1 = i
		elif i > Max_2:
			Max_2 = i
	return min(Max_2 - 1, N - 2)
T = int(input())
for i in range(T):
	N = int(input())
	A = input().split()
	A = list(map(int, A))
	print(max_ladder(A, N))


mod = 1000000007
eps = 10 ** (-9)

def main():
	import sys
	input = sys.stdin.buffer.readline
	for _ in range(int(input())):
		N = int(input())
		A = list(map(int, input().split()))
		A.sort()
		print(min(N - 2, A[-2] - 1))
main()


for _ in range(int(input())):
	n = int(input())
	a = sorted([int(i) for i in input().split()])
	k = min(a[-1] - 1, a[-2] - 1, len(a) - 2)
	print(k)


from __future__ import division, print_function
mod1 = int(1000000000.0 + 7)
from sys import stdin, stdout
import bisect
from bisect import bisect_left as bl
from bisect import bisect_right as br
import itertools
from collections import Counter
import collections
import math
import heapq
import re

def modinv(n, p):
	return pow(n, p - 2, p)

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())

def Divisors(n):
	l = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l

def most_frequent(list):
	return max(set(list), key=list.count)

def GCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def ncr(n, r, p):
	t = fact[n] * (ifact[r] * ifact[n - r] % p) % p
	return t

def Convert(string):
	li = list(string.split(''))
	return li

def SieveOfEratosthenes(n):
	global prime
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	f = []
	for p in range(2, n):
		if prime[p]:
			f.append(p)
	return f
prime = []
q = []

def dfs(n, d, v, c):
	global q
	v[n] = 1
	x = d[n]
	q.append(n)
	j = c
	for i in x:
		if i not in v:
			f = dfs(i, d, v, c + 1)
			j = max(j, f)
	return j

def main():
	for i in range(inin()):
		n = inin()
		a = ain()
		a.sort()
		ans = 0
		if len(a) < 3:
			print(0)
			continue
		print(min(a[-2] - 1, n - 2))
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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()


t = int(input())
for _ in range(t):
	n = int(input())
	v = sorted(list(map(int, input().split())))
	if len(v) <= 2:
		print(0)
	else:
		print(min(n - 2, v[-2] - 1))


T = int(input())
for _ in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	ans = min(a[-2] - 1, n - 2)
	print(ans)


T = int(input())
for i in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	if a[-2] == 1:
		print(0)
	else:
		print(min(a[-2] - 1, n - 2))


for _ in range(int(input())):
	input()
	a = list(map(int, input().split()))
	print(min(sorted(a, reverse=True)[1] - 1, len(a) - 2))


n = int(input())
for _ in range(n):
	T = int(input())
	a = sorted(list(map(int, input().rstrip().split())), reverse=True)
	if T > 2:
		l = min(a[0], a[1])
		if l >= T - 1:
			print(T - 2)
		else:
			print(l - 1)
	else:
		print(0)


t = int(input().strip())
for i in range(t):
	n = int(input().strip())
	nums = [int(i) for i in input().strip().split()]
	ans = 0
	base1 = max(nums)
	for i in range(n):
		if nums[i] == base1:
			nums[i] = 0
			break
	base2 = max(nums)
	print(min(base1, base2) - 1 if min(base1, base2) - 1 < n - 2 else n - 2)


q = int(input())
result = ''
while q > 0:
	totalSticks = int(input())
	sticks = input()
	sticks = sticks.rsplit()
	intSticks = []
	for i in sticks:
		intSticks.append(int(i))
	intSticks.sort()
	height = min(intSticks.pop(), intSticks.pop())
	if height > 1:
		result += str(min(height - 1, len(intSticks)))
	else:
		result += '0'
	result += '\n'
	q -= 1
print(result)


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))[:n]
	l.sort(reverse=True)
	c = l[1] - 1
	print(min(c, n - 2))


t = int(input())
for i in range(t):
	n = int(input())
	lad = list(map(int, input().split()))
	lad.sort(reverse=True)
	l1 = lad[0]
	l2 = lad[1]
	res = lad[1] - 1
	mlen = len(lad) - 2
	if lad[1] == 0:
		print(0)
	elif mlen < res:
		print(mlen)
	elif mlen >= res:
		print(res)


for u in range(int(input())):
	n = int(input())
	l = sorted(list(map(int, input().split())), reverse=True)
	print(min(n - 2, l[1] - 1))


def f(l):
	if len(l) < 3:
		return 0
	l.sort()
	return min(l[-2] - 1, len(l) - 2)
t = int(input())
for _ in range(t):
	_ = input()
	l = list(map(int, input().split()))
	print(f(l))


t = int(input())
while t:
	t -= 1
	n = int(input())
	a = sorted(list(map(int, input().split())), reverse=True)
	if n == 2:
		print(0)
	else:
		print(min(a[1] - 1, n - 2))


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	a.sort()
	rungs = n - 2
	b = [a[n - 2], a[n - 1]]
	print(min(min(b) - 1, n - 2))


t = int(input())
for i in range(t):
	n = int(input())
	arr = [int(j) for j in input().split()]
	if n == 2:
		print(0)
		continue
	arr.sort()
	x = arr[-2]
	rem = n - 2
	if rem <= x - 1:
		print(rem)
	else:
		print(x - 1)


t = int(input())
for tt in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	n -= 2
	x = l[-2] - 1
	print(min(x, n))


consultas = int(input())
for e in range(consultas):
	tabuas = int(input())
	comprimentos = input().split()
	bases = []
	degraus = 0
	if tabuas < 3:
		print(0)
		continue
	for i in range(len(comprimentos)):
		comprimentos[i] = int(comprimentos[i])
	comprimentos.sort(reverse=True)
	if comprimentos[0] > 1 and comprimentos[1] > 1:
		bases.append(comprimentos[0])
		bases.append(comprimentos[1])
	else:
		print(0)
		continue
	for i in range(2, len(comprimentos)):
		if degraus + 1 < min(bases):
			degraus += 1
		else:
			break
	print(degraus)


t = int(input())
for t in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	a.sort()
	if n <= 2:
		res = 0
	else:
		res = min(n - 2, a[-2] - 1)
	print(res)


def func(a):
	a = [int(i) for i in a.split()]
	a.sort(reverse=True)
	base = min(a[:2])
	step = a[2:]
	return min(base - 1, len(step))

def main():
	t = int(input())
	t_input = []
	for i in range(t):
		input()
		t_input.append(input())
	for i in [func(a) for a in t_input]:
		print(i)
main()


n1 = int(input())
for x in range(n1):
	n = int(input())
	a = input().split()
	for x in range(len(a)):
		a[x] = int(a[x])
	a = sorted(a, reverse=True)
	resposta = min(n - 2, a[1] - 1)
	print(resposta)


for _ in range(int(input())):
	n = int(input()) - 2
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	print(min(n, a[1] - 1))


t = int(input())
arr = [(int(input()), list(map(int, input().split()))) for _ in range(t)]
for i in range(t):
	if arr[i][0] <= 2:
		print(0)
	else:
		max_val1 = max(arr[i][1])
		del arr[i][1][arr[i][1].index(max_val1)]
		max_val2 = max(arr[i][1])
		del arr[i][1][arr[i][1].index(max_val2)]
		print(min(arr[i][0] - 2, max_val2 - 1))


T = int(input())
for i in range(T):
	n = int(input())
	x = [int(x) for x in input().split()]
	x.sort(reverse=True)
	print(min(n - 2, x[1] - 1))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	if a[-2] > n - 2:
		print(n - 2)
	else:
		print(a[-2] - 1)


q = int(input())
for _ in range(q):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	h = a[-2]
	steps = n - 2
	print(min(h - 1, steps))


t = int(input())
for _ in range(t):
	n = int(input())
	l = sorted(list(map(int, input().split())))
	l = l[::-1]
	if l[0] > 1 and l[1] > 1:
		a = min(n - 2, l[1] - 1)
		print(a)
	else:
		print('0')


t = int(input())
queryList = list()
query = list()
ans = list()
while t > 0:
	k = input()
	query = list(map(int, input().split()))
	query.sort()
	query.reverse()
	n1 = query[1] - 1
	n2 = len(query) - 2
	if n1 < n2:
		ans.append(n1)
	else:
		ans.append(n2)
	query.clear()
	t = t - 1
for k in ans:
	print(k)


def program():
	n = int(input())
	l = list(map(int, input().split()))
	m = max(l)
	l.remove(m)
	m = max(l)
	print(min(m - 1, n - 2))
t = int(input())
for i in range(t):
	program()


from sys import stdin, stdout

def input():
	input.IT += 1
	return input.lines[input.IT - 1][:-1]
input.IT = 0
input.lines = stdin.readlines()

def print(*arg):
	print.out.append(' '.join((str(i) for i in arg)))
print.out = []
for _ in range(int(input())):
	n = int(input())
	a = sorted(map(int, input().split()), reverse=True)
	print(min(a[0] - 1, a[1] - 1, n - 2))
stdout.write('\n'.join(print.out))


for i in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	m1 = max(l)
	l.remove(m1)
	m2 = max(l)
	l.remove(m2)
	for j in l:
		if j < 1:
			l.remove(j)
	k = len(l)
	if k + 1 <= min(m1, m2):
		print(k)
	else:
		print(min(m1, m2) - 1)


t = int(input())
for halua in range(t):
	n = int(input())
	planks = list(map(int, input().split()))
	planks.sort()
	lambai_possible = planks[n - 2] - 1
	k = 0
	for x in range(n - 2):
		if planks[x] >= 1:
			k += 1
	if k > lambai_possible:
		print(lambai_possible)
	else:
		print(k)


from sys import stdin
read = stdin.readline

def upper_bound(S, t):
	(lower, upper) = (0, len(S))
	while lower < upper:
		mid = (lower + upper) // 2
		if S[mid] > t:
			upper = mid
		elif S[mid] <= t:
			lower = mid + 1
	return upper
T = int(read())
for t in range(T):
	n = int(read())
	s = sorted(map(int, read().split()))
	print(min(s[-2] - 1, n - upper_bound(s, 0) - 2))


from sys import stdin
input = stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort()
	ans = min(n - 2, a[-2] - 1)
	print(ans)


t = int(input())
for test in range(t):
	n = int(input())
	nums = sorted(list(map(int, input().split())))
	print(min(n - 2, nums[-2] - 1))


t = int(input())
for nt in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	temp = min(l[-1], l[-2])
	print(min(n - 2, temp - 1))


n = int(input())
for i in range(n):
	p = int(input())
	a = list(map(int, input().split()))
	a = sorted(a)
	if p == 2:
		print(0)
		continue
	k = a[-2] - 1
	print(min(k, p - 2))


def ladder():
	n_o_p = int(input())
	a = list(map(int, input().split()))
	a.sort()
	a.reverse()
	if a[0] < 2 or a[1] < 2:
		print(0)
	else:
		print(min(min(a[0], a[1]) - 1, len(a) - 2))
n = int(input())
for i in range(n):
	ladder()


t = int(input())
ans = [None] * t
for j in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a = sorted(a)
	max1 = a[len(a) - 1]
	a.pop(len(a) - 1)
	max2 = a[len(a) - 1]
	a.pop(len(a) - 1)
	if max2 == 1:
		ans[j] = 0
		continue
	else:
		if len(a) >= max2:
			ans[j] = max2 - 1
			continue
		if len(a) < max2:
			ans[j] = len(a)
			continue
for i in range(t):
	print(ans[i])


from math import *
from itertools import *
from collections import *
from bisect import *
T = int(input())
for _ in range(T):
	n = int(input())
	lst = [int(x) for x in input().split()]
	lst.sort(reverse=True)
	k = lst[1] - 1
	ans = max(0, min(k, len(lst) - 2))
	print(ans)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	if n == 3:
		if arr[-1] >= 2 and arr[-2] >= 2 and (arr[0] > 0):
			print(1)
		else:
			print(0)
	else:
		print(min(n - 2, arr[-2] - 1))


for i in range(int(input())):
	n = int(input()) - 2
	t = list(map(int, input().split()))
	t.remove(max(t))
	k = max(t) - 1
	if n < k:
		print(n)
	else:
		print(k)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	ma1 = max(l)
	l.remove(ma1)
	ma2 = max(l)
	print(min(ma2 - 1, n - 2))


T = int(input())
for i in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	a = sorted(a, reverse=True)
	if n <= 2:
		print(0)
	else:
		print(max(0, min(a[1] - 1, len(a) - 2)))


t = int(input())
l2 = []
for i in range(t):
	n = int(input())
	l1 = [int(a) for a in input().split()]
	max1 = 0
	max2 = 0
	for k in range(n):
		if l1[k] >= max1:
			max2 = max1
			max1 = l1[k]
		elif l1[k] > max2:
			max2 = l1[k]
		else:
			continue
	c = 0
	for k in range(n):
		if l1[k] <= max1:
			c += 1
	if c - 2 < max2:
		l2.append(c - 2)
	else:
		l2.append(max2 - 1)
for i in range(t):
	print(l2[i])


n = int(input())
for i in range(n):
	planks = int(input())
	sizes = list(map(int, input().split()))
	sizes.sort(reverse=True)
	if planks >= 3:
		bigA = sizes[0]
		bigB = sizes[1]
		count = 0
		for j in range(len(sizes)):
			if j == 0 or j == 1:
				continue
			if count + 2 <= bigB:
				count += 1
		print(count)
	else:
		print(0)


t = int(input(''))
for i in range(t):
	n = int(input(''))
	arr = list(map(int, input().split()))
	arr.sort()
	cnt = -1
	sol = arr[n - 2] - 1
	print(min(sol, n - 2))


def ladders(n, arr):
	maxi = 0
	if arr[-1] > 1 < arr[-2]:
		maxi = arr[-2] - 1
	if maxi > n - 2:
		maxi = n - 2
	return maxi
for _ in range(int(input())):
	n = int(input())
	arr = sorted(list(map(int, input().split())))
	print(ladders(n, arr))


q = int(input())
for qq in range(q):
	n = int(input())
	dat = list(map(int, input().split()))
	dat.sort()
	(a, b) = (dat[-2], dat[-1])
	(a, b) = (a - 1, b - 1)
	dat = dat[:-2]
	l = len(dat)
	print(min(a, b, l))


def fun(z):
	z.sort()
	if len(z) < 3:
		return 0
	k1 = z[-2] - 1
	if k1 < 1:
		return 0
	return min([k1, len(z) - 2])
number = int(input())
acc = []
for _ in range(number):
	elN = int(input())
	a = [int(i) for i in input().split(' ')]
	acc.append(fun(a))
for i in acc:
	print(i)


for tt in range(int(input())):
	q = int(input())
	l = [int(i) for i in input().split()]
	if q < 3:
		print('0')
		continue
	else:
		l.sort(reverse=True)
		if l[1] == 1:
			print('0')
			continue
		print(min(l[1] - 1, q - 2))


q = int(input())
for _ in range(q):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	x = min(l[len(l) - 1], l[len(l) - 2])
	ans = min(x - 1, n - 2)
	print(ans)


t = int(input())
while t:
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	count = 0
	min_base = arr[len(arr) - 2]
	for i in range(len(arr) - 2):
		if arr[i] >= 1 and count < min_base - 1:
			count += 1
	print(count)
	t -= 1


def main():
	t = int(input())
	for i in range(0, t):
		n = int(input())
		a = list(map(int, input().split()))
		a.sort()
		k = a[-2] - 1
		print(min(n - 2, k))
main()


n = int(input())
for _ in range(n):
	np = int(input())
	l = list(map(int, input().split()))
	l.sort(reverse=True)
	if np - 2 >= l[1] - 1:
		print(l[1] - 1)
	elif l[1] == 1:
		print(0)
	else:
		print(np - 2)


t = int(input())
for case in range(t):
	n = int(input())
	a = [int(x) for x in input().split(' ')]
	for i in range(2):
		m = max(a)
		a.remove(m)
	ans = max(min(m - 1, n - 2), 0)
	print(ans)


for iw in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	A.sort(reverse=True)
	print(min(A[1] - 1, n - 2))


T = int(input())
for _ in range(T):
	n = int(input())
	x = sorted(map(int, input().split()), reverse=True)
	print(min(x[1] - 1, n - 2))


t = int(input())
for w in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	ma = arr[-1]
	mb = arr[-2]
	mm = min(ma - 1, mb - 1)
	ans = min(mm, n - 2)
	print(ans)


n = int(input())
for i in range(n):
	input()
	p = sorted(map(int, input().split()))
	print(min(p[-1] - 1, p[-2] - 1, len(p) - 2))


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	a1 = max(arr[-2] - 1, 0)
	a2 = n - 2
	print(min(a1, a2))


T = int(input())
ss = []
for i in range(T):
	n = int(input())
	s = map(int, input().split())
	s = list(s)
	s.remove(max(s))
	c = max(s)
	s.remove(max(s))
	if len(s) < c:
		ss.append(len(s))
	else:
		ss.append(c - 1)
for i in range(len(ss)):
	print(ss[i])


t = int(input())
while t:
	t -= 1
	n = int(input())
	ip = list(map(int, input().split()))
	ip.sort(reverse=True)
	m = ip[1]
	del ip[0]
	del ip[0]
	if m == 1:
		print(0)
		continue
	print(min(m - 1, len(ip)))


for _ in range(int(input())):
	n = int(input())
	lst = sorted(list(map(int, input().split())))
	(a, b) = (lst[-1], lst[-2])
	m = min(a, b) - 1
	ladder = n - 2
	print(min(m, ladder))


T = int(input())
ans = []
for _ in range(T):
	N = int(input())
	A = list(map(int, input().split()))
	A.sort(reverse=True)
	ma = A[1] - 1
	ans.append(min(ma, N - 2))
for a in ans:
	print(a)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	c = 0
	for j in range(2, n):
		if a[j] >= 1:
			c += 1
	if c + 1 > a[1]:
		c = a[1] - 1
	print(c)


def mp():
	return map(int, input().split())
t = int(input())
for tt in range(t):
	n = int(input())
	a = list(mp())
	a[a.index(max(a))] = 0
	print(min(n - 2, max(a) - 1))


for i in range(int(input())):
	a = int(input())
	t = list(map(int, input().split()))
	t.sort()
	h = 0
	b = t[-1]
	c = t[-2]
	if a - 2 <= min(b, c) - 1:
		print(a - 2)
	elif a - 2 > min(b, c) - 1:
		print(min(b, c) - 1)
	else:
		print(0)


Input = lambda : map(int, input().split())
for i in range(int(input())):
	n = int(input())
	l = sorted(list(Input()))
	k = l[-2] - 1
	y = n - 2
	print(min(k, y))


for _ in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	m = a[n - 2] - 1
	if n - 2 >= m:
		print(m)
	else:
		print(n - 2)


T = int(input())
while T:
	n = int(input())
	a = [int(_) for _ in input().split(' ')]
	(max_1, max_2) = (max(a[0], a[1]), min(a[0], a[1]))
	for i in range(2, n):
		if a[i] > max_1:
			(max_1, max_2) = (a[i], max_1)
		elif a[i] > max_2:
			max_2 = a[i]
	print(min(min(max_2, max_1) - 1, n - 2))
	T = T - 1


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort(reverse=True)
	print(min(a[1] - 1, n - 2))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	if len(l) < 3:
		print(0)
	else:
		l.sort(reverse=True)
		a = l[0]
		b = l[1]
		ch = min(a, b)
		rem = len(l) - 2
		k = min(rem, ch - 1)
		if ch < k + 1:
			k = 0
		print(k)


t = int(input())
for x in range(t):
	n = int(input())
	l1 = [int(x) for x in input().split()]
	l1.sort(reverse=True)
	if l1[0] < 2:
		print(0)
	else:
		print(min(l1[1] - 1, len(l1) - 2))


t = int(input())
for i in range(t):
	totalwoods = int(input())
	woods = input().split()
	woods = [int(x) for x in woods]
	woods.sort()
	(base1, base2) = (woods[totalwoods - 1], woods[totalwoods - 2])
	planks = 0
	if base1 < 2 or base2 < 2:
		print(0)
		continue
	while planks < totalwoods - 2 and planks + 1 < base1 and (planks + 1 < base2):
		planks += 1
	print(planks)


for i in range(int(input())):
	num = int(input())
	data = [int(i) for i in input().split()]
	data.sort()
	k0 = min(data[-2] - 1, num - 2)
	print(max(0, k0))


t = int(input())
count = 0

def maximum(x):
	num = 0
	index = 0
	for i in range(len(x)):
		if x[i] > num:
			num = x[i]
			index = i
	return [num, index]
for i in range(t):
	planks = int(input())
	lst = list(map(int, input().split()))
	if planks > 2:
		result = maximum(lst)
		new_lst = lst
		lst.pop(result[1])
		a = result[0]
		result = maximum(new_lst)
		b = result[0]
		if 1 <= len(lst) - 1 < b:
			print(len(lst) - 1)
		elif len(lst) - 1 > b:
			print(b - 1)
		elif len(lst) - 1 == b and 2 <= len(lst) - 1:
			print(len(lst) - 2)
		else:
			print(0)
	else:
		print(0)


t = int(input())
for _ in range(t):
	n = int(input())
	array = list(map(int, input().split()))
	if n < 2:
		print(0)
	else:
		array.sort()
		steps = [array[-1], array[-2]]
		array.pop()
		array.pop()
		x = steps[1] - 1
		y = len(array)
		print(min(x, y))


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	m1 = max(a)
	a.remove(max(a))
	m2 = max(a)
	a.remove(max(a))
	print(min(m2 - 1, len(a)))


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	lista = list(map(int, input().split()))
	lista.sort()
	sec = lista[len(lista) - 2] - 1
	print(max(min(len(lista) - 2, sec), 0))


def solve(n, data: list) -> int:
	data.sort()
	maxK = data[-2] - 1
	while maxK != 0:
		if len(data) >= maxK + 2:
			return maxK
		else:
			maxK -= 1
	return maxK
T = int(input())
for _ in range(T):
	n = int(input())
	data = map(int, input().split())
	result = solve(n, list(data))
	print(result)


a = int(input())
for i in range(a):
	b = int(input())
	i = sorted(map(int, input().split()), reverse=True)
	print(min(i[1] - 1, b - 2))


t = int(input())
for i in range(t):
	n = int(input())
	lens = sorted(map(int, input().split()))
	cnt = len(list(filter(lambda x: x > 0, lens[:-2])))
	print(min(cnt, lens[-2] - 1))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	i = 0
	while a[i] < 1 and i < n:
		i = i + 1
	if i >= n - 2:
		print(0)
	else:
		print(min(n - 2 - i, a[n - 2] - 1))


def check(lst):
	count = 0
	for i in range(len(lst) - 2):
		if lst[i] > 0:
			count += 1
	return min(count, lst[-2] - 1)
b = list()
t = int(input())
for i in range(t):
	n = int(input())
	c = [int(j) for j in input().split()]
	b.append(check(sorted(c)))
for y in b:
	print(y)


T = int(input())
for _ in range(T):
	n = int(input())
	line = input()
	arr = [int(i) for i in line.split(' ')]
	arr.sort(reverse=True)
	ans = 0
	if n < 3:
		print(0)
		continue
	print(min(arr[1] - 1, n - 2))


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().strip().split()))
	a.sort()
	steps = n - 2
	print(min(steps, a[n - 1] - 1, a[n - 2] - 1))


TC = int(input())
for tc in range(TC):
	N = int(input())
	A = list(map(int, input().split()))
	A.sort()
	print(min(A[-2] - 1, N - 2))


for _ in range(int(input())):
	n = int(input()) - 2
	a = list(map(int, input().split()))
	a.remove(max(a))
	p = max(a) - 1
	print(min(n, p))


q = int(input())
for _ in range(q):
	n = int(input())
	a = [int(x) for x in input().split()]
	a = sorted(a)
	if n == 2 or a[-2] == 1:
		print(0)
	else:
		print(min(a[-2] - 1, len(a) - 2))


T = int(input())
list2 = []
for i in range(T):
	n = int(input())
	list1 = [int(i) for i in input().split()]
	list1.remove(max(list1))
	a = max(list1)
	u = min(a - 1, n - 2)
	list2.append(u)
for i in list2:
	print(i)


T = int(input())
for _ in range(T):
	N = int(input())
	s = [int(x) for x in input().split()]
	arr = sorted(s)
	if N < 3:
		print(0)
	else:
		t = min(arr[-1], arr[-2])
		if t < 2:
			print(0)
		else:
			ans = min(len(arr) - 2, t - 1)
			print(ans)


import io, sys
input = lambda f=io.StringIO(sys.stdin.buffer.read().decode()).readline: f().rstrip()
ii = lambda : int(input())
mi = lambda : map(int, input().split())
li = lambda : list(mi())
for _ in range(ii()):
	n = ii()
	a = li()
	a.sort()
	ans = 0
	for i in range(n - 1):
		ans = max(ans, min(i, a[i] - 1))
	print(ans)


for _ in range(int(input())):
	n = int(input())
	k = list(map(int, input().split()))
	k.remove(max(k))
	l = max(k)
	print(min(l - 1, len(k) - 1))


T = int(input())
for _ in range(T):
	n = int(input())
	a = [int(w) for w in input().split()]
	a.sort()
	print(min(a[-2] - 1, n - 2))


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	if n <= 2:
		print(0)
	else:
		count = n - 2
		mini = a[n - 2] - 1
		mini = min(n - 2, mini)
		print(mini)


t = int(input())
for i in range(t):
	n = int(input())
	list = [x for x in map(int, input().split())]
	list.sort()
	print(min(len(list) - 2, list[len(list) - 2] - 1))


for _ in range(int(input())):
	n = int(input())
	a = sorted(map(int, input().split()))
	(x, y) = (a.pop(), a.pop())
	print(max(0, min(x - 1, y - 1, n - 2 - a.count(0))))


t = int(input())
while t > 0:
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort(reverse=True)
	m1 = a[0]
	m2 = a[1]
	i = n - 3
	flag = 0
	while i >= 0:
		if m1 >= i + 2 and m2 >= i + 2:
			print(i + 1)
			flag = 1
			break
		i -= 1
	if flag == 0:
		print(0)
	t -= 1


for t in range(int(input())):
	n = int(input())
	a = list(sorted(map(int, input().split())))
	if n < 3:
		print(0)
	else:
		mi = min(a[n - 1], a[n - 2])
		ans = 0
		for i in range(n - 2):
			if a[i] <= mi and ans + 1 < mi:
				ans += 1
			else:
				break
		print(ans)


TestCase = int(input())
while TestCase > 0:
	N = int(input())
	listi = list(map(int, input().split()))
	listi.sort()
	large = listi[-1]
	Slarge = listi[-2]
	print(min(Slarge - 1, N - 2))
	TestCase -= 1


t = int(input())
for you in range(t):
	n = int(input())
	l = input().split()
	li = [int(i) for i in l]
	li.sort()
	z = li[-2] - 1
	print(min(z, n - 2))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	(max1, max2) = (a[-1], a[-2])
	print(min(n - 2, max2 - 1))


num = int(input())
for i in range(num):
	nobodycares = input()
	x = list(map(int, input().split()))
	b1 = max(x)
	x.remove(b1)
	b2 = max(x)
	if len(x) - 1 < b2:
		print(len(x) - 1)
	else:
		print(b2 - 1)


t = int(input())
for i in range(t):
	n = int(input())
	ar = list(map(int, input().split()))
	if n <= 2:
		print(0)
		continue
	ar = sorted(ar)[::-1]
	ans = 0
	for i in range(1, n - 1):
		if ar[0] > i and ar[1] > i:
			ans = i
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	xx = a[-2]
	aa = 0
	for i in a[0:-2]:
		if i >= 1:
			aa += 1
	if aa >= xx:
		print(xx - 1)
	else:
		print(aa)


t = int(input())
while t:
	t -= 1
	n = int(input())
	k = n - 2
	l = list(map(int, input().strip().split(' ')))
	l.sort()
	possible = False
	ans = 0
	while k >= 1:
		bs = k + 1
		if l[n - 1] >= bs and l[n - 2] >= bs:
			ans = k
			possible = True
			break
		else:
			k -= 1
	if possible == True:
		print(ans)
	else:
		print('0')


t = int(input())
kq = []
for i in range(0, t):
	base = [0, 0]
	n = int(input())
	na = input()
	na = na.split()
	for i in range(0, n):
		na[i] = eval(na[i])
	base[0] = max(na)
	na.pop(na.index(max(na)))
	base[1] = max(na)
	na.pop(na.index(max(na)))
	if min(base) - 1 >= n - 2:
		kq = kq + [n - 2]
	else:
		kq = kq + [min(base) - 1]
for i in range(0, t):
	print(kq[i])


from collections import defaultdict, deque
import sys, heapq, bisect, math, itertools, string, queue, copy, time
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
mod = 10 ** 9 + 7
eps = 10 ** (-7)

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

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

def inpl_str():
	return list(input().split())
T = inp()
for _ in range(T):
	N = inp()
	aa = inpl()
	aa.sort()
	(l, r) = (aa[-1], aa[-2])
	print(min(N - 2, l - 1, r - 1))


T = int(input())
for i in range(T):
	n = int(input())
	A = list(map(int, input().split()))
	A.sort(reverse=True)
	k = A[1]
	lll = len(A)
	if k > lll - 2:
		print(lll - 2)
	elif k == lll - 2:
		print(lll - 3)
	elif k < lll - 2:
		print(k - 1)


def ladder():
	numberOfTimes = int(input())
	for i in range(numberOfTimes):
		count = 0
		planks = int(input())
		sizes = input().split()
		for j in range(len(sizes)):
			sizes[j] = int(sizes[j])
		sizes.sort()
		leftLeg = sizes[planks - 1] - 1
		rightLeg = sizes[planks - 2] - 1
		maxsize = min(leftLeg, rightLeg)
		for i in range(len(sizes) - 2):
			count += 1
		output = min(maxsize, count)
		print(output)
ladder()


def second_largest(numbers):
	count = 0
	m1 = m2 = float('-inf')
	for x in numbers:
		count += 1
		if x > m2:
			if x >= m1:
				(m1, m2) = (x, m1)
			else:
				m2 = x
	return m2 if count >= 2 else None
tc = int(input())
for _ in range(tc):
	n = int(input())
	ls = [int(i) for i in input().split()]
	mx = second_largest(ls)
	print(min(mx - 1, n - 2))


i = int(input())
ans = []
for _ in range(i):
	a = int(input())
	b = list(map(int, input().split()))
	b.sort()
	h = b[-2]
	p = max(0, min(a - 2, h - 1))
	ans.append(p)
for i in ans:
	print(i)


t = int(input())
for i in range(t):
	n = int(input())
	ar = list(map(int, input().split()))
	ar = sorted(ar)
	if n < 3:
		print(0)
	else:
		direct = min(ar[-1], ar[-2])
		if direct < 2:
			print(0)
		else:
			left = n - 2
			print(max(min(left, direct - 1), 0))


t = int(input())
for i in range(t):
	n = int(input())
	boards = list(map(int, input().split()))
	first_max = 0
	second_max = 0
	for board in boards:
		if board > first_max:
			second_max = first_max
			first_max = board
		elif board > second_max:
			second_max = board
	if n - 2 >= second_max - 1:
		print(second_max - 1)
	else:
		print(n - 2)


a = int(input())
k = 0
while k < a:
	k += 1
	x = int(input())
	m = list(map(int, input().split(' ')))
	m.sort()
	c = m[-2] - 1
	print(min(c, x - 2))


import sys
import math
input = sys.stdin.readline
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort(reverse=True)
	print(min(arr[1] - 1, n - 2))


import sys

def rs():
	return sys.stdin.readline().rstrip()

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

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

def ws(s):
	sys.stdout.write(s)
	sys.stdout.write('\n')

def wi(n):
	sys.stdout.write(str(n))
	sys.stdout.write('\n')

def wia(a, sep=' '):
	sys.stdout.write(sep.join([str(x) for x in a]))
	sys.stdout.write('\n')

def main():
	for _ in range(ri()):
		n = ri()
		a = ria()
		a = sorted(a, reverse=True)
		wi(min(a[1] - 1, n - 2))
main()


for _ in range(int(input())):
	n = int(input())
	l = sorted(map(int, input().split()))
	print(min(l[-2] - 1, n - 2))


T = int(input())
while T:
	n = int(input())
	a = [int(_) for _ in input().split(' ')]
	a.sort()
	max_1 = a[-1]
	max_2 = a[-2]
	print(min(min(max_2, max_1) - 1, n - 2))
	T = T - 1


t = int(input())
for i in range(t):
	n = int(input())
	lst = list(map(int, input().strip().split(' ')))
	lst.sort(reverse=True)
	if n - 2 >= lst[1]:
		print(lst[1] - 1)
	else:
		print(n - 2)


n = int(input())
for i in range(n):
	m = int(input())
	a = []
	a = input().split()
	b = []
	for j in a:
		b.append(int(j))
	b.sort()
	if b[-2] > m - 2:
		print(m - 2)
	elif b[-2] > 1:
		print(b[-2] - 1)
	else:
		print(0)


def calculaSteps(entrada):
	valores = [int(valor) for valor in entrada]
	valores.sort(reverse=True)
	menor_placa_apoio = valores[1]
	cont = 0
	for i in range(2, len(entrada)):
		if cont < menor_placa_apoio - 1:
			cont += 1
		else:
			break
	return cont
repeticoes = int(input())
for i in range(repeticoes):
	num = int(input())
	entrada = input().split()
	print(calculaSteps(entrada))


T = int(input())
for t in range(T):
	n = int(input())
	planks = map(int, input().split())
	(max1, max2) = (0, 0)
	for p in planks:
		if p > max2:
			max2 = p
		if max2 > max1:
			(max1, max2) = (max2, max1)
	print(int(min(max2 - 1, n - 2)))


for i in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	a = min(arr[-1], arr[-2])
	if a == 1 or n == 2:
		print(0)
	elif n - 2 > a - 1:
		print(a - 1)
	else:
		print(n - 2)


q = int(input())
for i in range(q):
	k = int(input())
	a = list(map(int, input().split()))
	a = list(sorted(a))
	print(min(a[k - 2] - 1, k - 2))


n = int(input())
ans = list()
for j in range(n):
	m = int(input())
	x = list(map(int, input().split()))
	x.sort()
	k = x[-2] - 1
	if k == 0:
		ans.append(0)
	else:
		ans.append(min(k, m - 2))
for j in range(n):
	print(ans[j])


for _ in ' ' * int(input()):
	a = int(input())
	print(min(a - 2, min(sorted(map(int, input().split()))[a - 2:]) - 1))


CASES = int(input())
for i in range(CASES):
	n = int(input())
	s = sorted(list(map(int, input().split())), reverse=True)
	if n <= 2:
		print(0)
	else:
		r1 = min(s[:2]) - 1
		r2 = n - 2
		print(max(min(r1, r2), 0))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	x = a[len(a) - 1]
	y = a[len(a) - 2]
	z = len(a) - 2
	m = min(x, y)
	if m > z:
		print(z)
	elif m == z:
		print(z - 1)
	else:
		print(m - 1)


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	x = l[n - 2]
	k = n - 2
	if k >= x:
		tmp = x - 1
	else:
		tmp = k
	print(tmp)


for _ in range(int(input())):
	n = int(input())
	a = sorted(map(int, input().split()), reverse=True)
	print(min(a[1] - 1, max(0, n - 2)))


def solve(a, n):
	a.sort()
	ans = a[-2]
	return min(ans - 1, n - 2)
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	print(solve(a, n))


T = int(input())
for case in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	if n <= 2 or a[-2] < 2:
		print(0)
		continue
	print(min(n - 2, a[-2] - 1))


T = int(input())
for _ in range(T):
	n = int(input())
	k = sorted(list(map(int, input().split())))
	m = k[n - 2]
	if m < 2:
		print(0)
	else:
		print(min(m - 1, n - 2))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if n <= 2:
		print(0)
	else:
		a.sort(reverse=True)
		print(min(n - 2, min(a[0], a[1]) - 1))


t = int(input())
for _ in range(t):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	mx1 = a.pop()
	mx2 = a.pop()
	if mx1 == mx2:
		print(min(mx1 - 1, n - 2))
	else:
		print(min(mx2 - 1, n - 2))


n = int(input())
for i in range(0, n):
	f = int(input())
	ln = [int(i) for i in input().split(' ')]
	ln = sorted(ln)
	k = min(ln[-2] - 1, len(ln[:-2]))
	print(k)


t = int(input())
Max = 0
for i in range(0, t):
	Max = 0
	(n, x) = (int(input()), list(map(int, input().split(' '))))
	x = sorted(x)
	for j in range(1, x[n - 2] + 1):
		if n - 2 >= j - 1:
			Max = max(Max, j - 1)
	print(Max)


import sys

class ADIYWoodenLadder:

	def solve(self):
		t = int(input())
		for _ in range(t):
			n = int(input())
			a = [int(_) for _ in input().split()]
			a.sort()
			print(min(a[-2] - 1, n - 2))
solver = ADIYWoodenLadder()
input = sys.stdin.readline
solver.solve()


for i in range(int(input())):
	a = int(input())
	p = list(sorted(map(int, input().split())))
	print(min(a - 2, p[-2] - 1))


import os
import sys
debug = True
if debug and os.path.exists('input.in'):
	input = open('input.in', 'r').readline
else:
	debug = False
	input = sys.stdin.readline

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

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

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

def invr():
	return map(int, input().split())
test_count = inp()
for t in range(test_count):
	if debug:
		print('Test Case #', t + 1)
	n = inp()
	a = inlt()
	a.sort(reverse=True)
	print(min(a[1] - 1, n - 2))


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	a.reverse()
	if len(a) == 2 or a[1] == 1:
		print(0)
	else:
		x = a[1] - 1
		y = len(a) - 2
		print(min(x, y))


n = int(input())
for i in range(n):
	q = int(input())
	a = []
	a = input().split(' ')
	for i in range(len(a)):
		a[i] = int(a[i])
	a.sort(reverse=True)
	if q == 2:
		print(0)
	elif a[1] - 1 > q - 2:
		print(q - 2)
	else:
		print(a[1] - 1)


for i in range(int(input())):
	n = int(input())
	arr = [int(i) for i in input().split()]
	step = n - 2
	m1 = 0
	m2 = 0
	for i in arr:
		if i > m1:
			m1 = i
		if m1 > m2:
			temp = m2
			m2 = m1
			m1 = temp
	if m1 >= n - 1:
		print(step)
	else:
		print(m1 - 1)


def main():
	test_case = int(input())
	while test_case:
		test_case -= 1
		num = int(input())
		p = list(map(int, input().split()))
		p = sorted(p)
		m = p[-2]
		print(min(num - 2, m - 1))
main()


import sys
T = int(sys.stdin.readline().strip())
for t in range(0, T):
	n = int(sys.stdin.readline().strip())
	a = list(map(int, sys.stdin.readline().strip().split()))
	a.sort()
	print(min([len(a) - 2, a[-2] - 1]))


T = int(input())
for _ in range(0, T):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	for i in range(n - 2, -1, -1):
		if a[0] >= i + 1 and a[1] >= i + 1 and (n >= 3):
			print(i)
			break
		elif n <= 2:
			print(0)
			break


Tc = int(input())
for i in range(0, Tc):
	n = int(input())
	data = list(map(int, input().strip().split()))
	data = sorted(data, reverse=True)
	mark = data[1] - 1
	count = 0
	for j in range(2, n):
		if data[j] > 0:
			count += 1
	if count > mark:
		print(mark)
	else:
		print(count)


n = int(input())
for i in range(n):
	k = int(input())
	s = list(map(int, input().split()))
	s.sort()
	print(min(k - 2, s[k - 2] - 1))


T = int(input())
sol = []
while T > 0:
	n = int(input())
	inp = input()
	a = [int(ele) for ele in inp.split()]
	a.sort()
	a.reverse()
	if n - 2 > a[1] - 1:
		sol.append(a[1] - 1)
	else:
		sol.append(n - 2)
	T -= 1
for ele in sol:
	print(ele)


import sys, math, queue
MOD = 998244353
sys.setrecursionlimit(1000000)
for _ in range(int(input())):
	n = int(input())
	a = sorted(map(int, input().split()))
	print(min(n - 2, min(a[-1], a[-2]) - 1))


for _ in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	a.reverse()
	if n == 2:
		print(0)
	elif n == 3:
		if a[1] > 1:
			print(1)
		else:
			print(0)
	else:
		for i in range(1, n - 1):
			if a[1] > n - 1 - i:
				print(n - 1 - i)
				break
		else:
			print(0)


T = int(input())
out = []
for i in range(T):
	k = 0
	n = int(input())
	lin = input()
	nums = lin.split(' ')
	for j in range(n):
		nums[j] = int(nums[j])
	list.sort(nums)
	napr_1 = list.pop(nums)
	napr_2 = list.pop(nums)
	if napr_1 < 2 or napr_2 < 2:
		out.append(k)
		continue
	num_stup = len(nums)
	k = num_stup
	if k >= min(napr_1, napr_2):
		k = min(napr_1, napr_2) - 1
	out.append(k)
for i in range(T):
	print(out[i])


import sys
input = sys.stdin.readline
Q = int(input())
for testcases in range(Q):
	n = int(input())
	A = list(map(int, input().split()))
	if n == 2:
		print(0)
		continue
	A.sort()
	x = A.pop()
	y = A.pop()
	MAX = y - 1
	print(min(MAX, len(A)))


t = int(input())
for x in range(t):
	n = int(input())
	le = list(map(int, input().split(' ')))
	le.sort(reverse=True)
	tt = le[1]
	count = 0
	for xx in range(2, n):
		if tt > count + 1 and le[xx] >= 1:
			count = count + 1
		else:
			break
	print(count)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	n1 = max(a)
	del a[a.index(max(a))]
	n2 = max(a)
	del a[a.index(max(a))]
	if n2 - 1 > len(a):
		print(len(a))
	else:
		print(n2 - 1)


T = int(input())
for k in range(0, T):
	n = int(input())
	vals = sorted([int(x) for x in input().split(' ')], reverse=True)
	if len(vals) < 3:
		print(0)
	else:
		k = min(vals[0], vals[1]) - 1
		if k < 1:
			print(0)
		else:
			k = min(k, len(vals) - 2)
			print(k)


for i in range(int(input())):
	z = 0
	x = int(input())
	y = [int(i) for i in input().split()]
	y.sort(reverse=True)
	for i in range(x - 2, 0, -1):
		if y[1] >= i + 1:
			print(i)
			z = 1
			break
	if z == 0:
		print(0)


T = int(input())
for i in range(T):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	print(min(len(l) - 2, l[-2] - 1))


t = int(input())
while t:
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	l.pop(len(l) - 1)
	a = l.pop(len(l) - 1)
	if a > len(l):
		print(len(l))
	else:
		print(a - 1)
	t = t - 1


o = ''
t = int(input())
for _ in range(t):
	n = int(input())
	a = sorted([int(i) for i in input().split(' ')])
	x = a.pop()
	y = a.pop()
	m = min(x, y)
	if len(a) < m:
		o += str(len(a)) + '\n'
	else:
		o += str(m - 1) + '\n'
print(o)


from sys import stdin, stdout
from collections import Counter
import math

def rsingle_int():
	return int(stdin.readline().rstrip())

def rmult_int():
	return [int(x) for x in stdin.readline().rstrip().split()]

def rmult_str():
	return stdin.readline().rstrip().split()

def r_str():
	return stdin.readline().rstrip()

def rsingle_char():
	return stdin.read(1)

def main():
	t = rsingle_int()
	for i in range(t):
		n = rsingle_int()
		a = rmult_int()
		max1 = 0
		max2 = 0
		for el in a:
			if el > max1:
				max2 = max1
				max1 = el
			elif el > max2:
				max2 = el
		print(min(n - 2, max2 - 1))
main()


for n in range(int(input())):
	j = int(input())
	s = sorted(list(map(int, input().split())))
	s = s[::-1]
	if j < 3:
		print(0)
	else:
		print(min(s[1] - 1, j - 2))


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	if len(a) < 3:
		print(0)
	else:
		m = min(a[0], a[1])
		print(min(m - 1, len(a) - 2))


t = int(input())
for z in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	mx = max(a)
	if a.count(mx) > 1:
		mx2 = mx
	else:
		mx2 = -1
		for i in a:
			if i > mx2 and i != mx:
				mx2 = i
	mn = min(mx2, mx)
	if mn - 1 >= n - 2:
		ans = n - 2
	else:
		ans = mn - 1
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	c = 0
	x = list(map(int, input().split()))
	x.sort()
	g = x[n - 2]
	for j in range(n - 2):
		if x[j] <= g:
			if c + 1 < g:
				c += 1
	print(c)


q = int(input())
for _ in range(q):
	n = int(input())
	a = sorted(map(int, input().split()))
	print(min(a[-2] - 1, len(a) - 2))


for _ in range(int(input())):
	k = int(input())
	l = list(map(int, input().split()))
	a = k - 2
	l.sort()
	b = l[k - 2] - 1
	print(min(a, b))


test = int(input())
for _ in range(test):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort(reverse=True)
	n = len(arr)
	print(min(arr[1] - 1, n - 2))


for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	print(min(n - 2, a[-2] - 1))


n = int(input())
for _ in range(n):
	k = int(input())
	data = list(map(int, input().split()))
	data.sort()
	print(min(data[-2] - 1, k - 2))


t = int(input())
for i in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	arr.sort(reverse=True)
	print(min(arr[1] - 1, len(arr) - 2))


for _ in range(int(input())):
	n = int(input())
	lad = list(map(int, input().split()))
	lad.sort(reverse=True)
	k = lad[1] - 1
	steps = n - 2
	print(min(steps, k))


t = int(input())
while t:
	n = int(input())
	planks = list(map(int, input().split()))
	planks.sort()
	p = min(planks[-2:])
	k = 0
	q = 0
	for i in planks[:-2]:
		if i < p:
			k += 1
		elif i == p:
			q += 1
	if k < p:
		if q > 0:
			if k + q < p:
				print(k + q)
			else:
				print(p - 1)
		else:
			print(k)
	else:
		print(p - 1)
	t -= 1


T = int(input())
for _ in range(T):
	n = int(input())
	aa = list(map(int, input().split()))
	aa.sort(reverse=True)
	if len(aa) < 3 or aa[1] < 2:
		print(0)
	else:
		print(min(aa[1] - 1, n - 2))


def solve():
	n = int(input())
	arr = [int(x) for x in input().split()]
	arr.sort(reverse=True)
	print(min(arr[1] - 1, n - 2))
kase = int(input())
for _ in range(kase):
	solve()


t = int(input())
for i in range(t):
	n = int(input())
	y = list(map(int, input().split()))
	y = sorted(y)
	if n == 2:
		print(0)
	else:
		x = min(y[-1], y[-2])
		if n - 2 < x:
			print(n - 2)
		elif n - 2 == x:
			print(n - 3)
		else:
			print(x - 1)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 1:
		print(0)
	else:
		max1 = max2 = -1
		for q in a:
			if q > max1:
				(max1, max2) = (q, max1)
			elif q > max2:
				max2 = q
		print(max(0, min(max2 - 1, len(a) - 2)))


for _ in range(int(input())):
	n = int(input())
	ls = [int(x) for x in input().split()]
	ls.sort()
	if n - ls[n - 2] < 0:
		print(n - 2)
	else:
		print(min(n - 2, ls[n - 2] - 1))


t = int(input())
for i in range(t):
	w = int(input())
	a = list(map(int, input().split()))
	a.sort()
	p = min(a[-1], a[-2])
	if w - 2 >= p - 1:
		print(p - 1)
	else:
		print(w - 2)


T = int(input())
results = []
for _ in range(T):
	n = int(input())
	lad = list((int(x) for x in input().split()))
	lad.sort(reverse=True)
	m_min = lad[1]
	lad_zero = list(filter(0 .__ne__, lad))
	steps = min(len(lad_zero) - 2, m_min - 1)
	results.append(steps)
for i in results:
	print(i)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	mx1 = 0
	mx2 = 0
	for i in a:
		if i > mx1:
			mx2 = mx1
			mx1 = i
		elif i > mx2:
			mx2 = i
	print(min(n - 2, mx2 - 1))


q = int(input())
for i in range(q):
	n = int(input())
	arr = [int(s) for s in input().split()]
	arr = sorted(arr)
	print(max(0, min(arr[n - 2] - 1, n - 2)))


p = int(input())
for i in range(p):
	q = int(input())
	a = sorted(list(map(int, input().split())))
	mx = 0
	for k in range(q - 1):
		if a[-1] >= k + 1 and a[-2] >= k + 1:
			mx = k
	print(mx)


T = int(input())
ans = []
for i in range(T):
	n = int(input())
	planks = input().split()
	planks = [int(ele) for ele in planks]
	planks.sort()
	if n == 2:
		ans.append(0)
		continue
	for k in range(n - 2, 0, -1):
		if planks[n - 1] >= k + 1 and planks[n - 2] >= k + 1:
			ans.append(k)
			break
	else:
		ans.append(0)
for k in ans:
	print(k)


t = int(input())
for i in range(t):
	total = int(input())
	planks = map(int, input().split(' '))
	planks = sorted(planks)
	maxSteps = planks[-2]
	print(min(maxSteps - 1, len(planks) - 2))


import sys
input = lambda : sys.stdin.readline().rstrip()
T = int(input())
for testcases in range(T):
	n = int(input())
	data = [int(v) for v in input().split()]
	data.sort()
	h = data[n - 2] - 1
	print(h if h < n - 2 else n - 2)


q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	x = a[0]
	y = a[1]
	m = min(x, y)
	l = len(a) - 2
	if n == 2:
		print(0)
	elif m == 1:
		print(0)
	else:
		ans = min(l, m - 1)
		print(ans)


for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	lis.sort()
	count = 0
	(x, y) = (lis[-1], lis[-2])
	z = min(x, y)
	for i in lis[:-2]:
		if i >= 1 and z - 1 != 0:
			count += 1
			if count >= z - 1:
				break
	print(count)


t = int(input())
for i in range(t):
	m1 = 0
	n = int(input())
	a = list(map(int, input().split()))
	m1 = max(a)
	a.remove(m1)
	m1 = max(a)
	a.remove(m1)
	m1 -= 1
	if len(a) >= m1:
		print(m1)
	else:
		print(len(a))


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort(reverse=True)
	x = a[0]
	y = a[1]
	if y <= 1 or n == 2:
		print(0)
	else:
		print(min(y - 1, n - 2))


t = int(input())
for test in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	a = sorted(a, reverse=True)
	if a[1] == 1:
		print(0)
	else:
		print(min(a[1] - 1, n - 2))


for _ in range(int(input().strip())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr = sorted(arr)
	if arr[n - 2] > n - 2:
		print(n - 2)
	else:
		print(arr[n - 2] - 1)


for _ in range(int(input())):
	n = int(input())
	wands = list(map(int, input().split()))
	a = max(wands)
	wands.remove(a)
	b = max(wands)
	wands.remove(b)
	count = 0
	n = n - 2
	while count < b - 1 and n != 0:
		count += 1
		n -= 1
	print(count)


def countk(A):
	n = max(A)
	A.remove(n)
	m = max(A)
	A.remove(m)
	if min(n, m) - 1 > len(A):
		return len(A)
	else:
		return min(n, m) - 1
T = int(input())
total = []
for i in range(T):
	n = int(input())
	a = [int(x) for x in input().strip().split()]
	total.append(countk(a))
for _ in range(len(total)):
	print(total[_])


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	b = a[n - 1]
	c = a[n - 2]
	d = 0
	for j in range(n - 2):
		if d < c - 1:
			d = d + 1
	print(d)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	arr = s.split(' ')
	max1 = 0
	max2 = 0
	for j in range(n):
		arr[j] = int(arr[j])
	arr.sort()
	if n == 2:
		print(0)
	elif arr[n - 2] - 1 >= n - 2:
		print(n - 2)
	else:
		print(arr[n - 2] - 1)


t = int(input())
for i in range(t):
	n = int(input())
	array = list(map(int, input().split()))
	array.sort(reverse=True)
	nup2 = array[1]
	if n - 2 < nup2:
		print(n - 2)
	else:
		print(nup2 - 1)


t = int(input())
while t > 0:
	n = int(input())
	arr = [int(i) for i in input().split()]
	arr.sort()
	if n >= 3:
		a = arr[n - 1]
		b = arr[n - 2]
		p = 0
		for i in range(n - 3, -1, -1):
			if b > p + 1:
				p += 1
			else:
				break
		print(p)
	else:
		print('0')
	t -= 1


for i in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort(reverse=True)
	r = min(arr[1] - 1, n - 2)
	print(r)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	if n == 2:
		print(0)
		continue
	a.sort(reverse=True)
	first = a[0]
	second = a[1]
	if first < 2 or second < 2:
		print(0)
		continue
	print(min(second - 1, n - 2))


n = int(input())
ans = []
for i in range(n):
	t = int(input())
	l = list(map(int, input().split()))
	l = sorted(l)
	ans.append(min(t - 2, l[-2] - 1))
for i in ans:
	print(i)


q = int(input())
for i in range(q):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	ans = 0
	for i in range(n - 2):
		if ans + 1 == l[-2]:
			break
		else:
			ans += 1
	print(ans)


T = int(input())
for _ in range(T):
	n = int(input())
	a = list(map(int, list(input().rstrip().split())))
	a = sorted(a)
	second_max = a[len(a) - 2]
	print(str(min(second_max - 1, n - 2)))


from sys import stdin, stdout
T = int(stdin.readline())
for i in range(T):
	N = int(stdin.readline())
	l = sorted(list(map(int, stdin.readline().split())))
	k = l[-2] - 1
	while True:
		if len(l[:-2]) >= k and sum(l[:-2]) >= k:
			stdout.write(str(k) + '\n')
			break
		else:
			if k == 0:
				stdout.write(str(0) + '\n')
				break
			k = k - 1


t = int(input())
while t:
	m = int(input())
	l = list(map(int, input().split()))
	l = sorted(l)
	mi = l[-2]
	if m - 2 >= mi:
		print(mi - 1)
	else:
		print(m - 2)
	t -= 1


import math
x = input()
x = int(x)
output = []
for i in range(x):
	a = input()
	a = int(a)
	numbers = list(map(int, input().split()))
	L = numbers.copy()
	L.sort()
	output.append(min(len(L) - 2, L[-2] - 1))
for i in range(x):
	print(output[i])


t = int(input())
for y in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	p = 0
	for i in range(n - 2, 0, -1):
		if l[n - 2] > i:
			p = i
			break
	print(p)


n = int(input())
for i in range(n):
	k = int(input())
	a = [int(i) for i in input().split()]
	p = max(a)
	a.remove(p)
	print(min(k - 2, max(a) - 1))


quer = int(input())
for _ in range(quer):
	num_plank = int(input())
	arr_raw = input().split()
	arr_plank = [int(x) for x in arr_raw]
	max_1_id = 0
	max_val_1 = arr_plank[0]
	result = num_plank - 2
	for i in range(1, num_plank):
		if arr_plank[i] > max_val_1:
			max_val_1 = arr_plank[i]
			max_1_id = i
	(arr_plank[max_1_id], arr_plank[0]) = (arr_plank[0], arr_plank[max_1_id])
	max_val_2 = arr_plank[1]
	for i in range(2, num_plank):
		if arr_plank[i] > max_val_2:
			max_val_2 = arr_plank[i]
	if max_val_2 - 1 < result:
		result = max_val_2 - 1
	print(result)


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	x = a[n - 2]
	if x == 1:
		print(0)
	else:
		print(min(n - 2, x - 1))


for t in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	if n < 3:
		ans = 0
	else:
		ans = min(min(a[-1], a[-2]) - 1, n - 2)
	print(ans)


tt = int(input())
while tt:
	n = int(input())
	l = [int(s) for s in input().split()]
	l.sort()
	print(min(n - 2, min(l[n - 1], l[n - 2]) - 1))
	tt -= 1


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	m = max(l)
	l.remove(m)
	m2 = max(l)
	l.remove(m2)
	lee = len(l)
	if m2 > lee:
		print(lee)
	else:
		print(m2 - 1)


t = int(input())
sets = []
for i in range(t):
	n = int(input())
	sets.append(list(map(int, input().split())))
for dset in sets:
	dset.sort()
	k = dset[-2]
	k = min(k - 1, len(dset) - 2)
	print(k)


def fun(a, b):
	if int(a) == 2:
		return 0
	b_list = map(int, b.split())
	b_l = sorted(b_list)
	max1 = b_l[-1]
	max2 = b_l[-2]
	if max1 == 1 or max2 == 1:
		return 0
	lim = min(max1, max2)
	if lim > int(a) - 2:
		return int(a) - 2
	else:
		return lim - 1
i = int(input())
for _ in range(i):
	a = input()
	b = input()
	z = fun(a, b)
	print(f'{z}\n')


for i in range(int(input())):
	input()
	li = sorted(list(map(int, input().split())))
	check = li[-2] - 1
	if len(li) - 2 < check:
		print(len(li) - 2)
	else:
		print(check)


t = input()
for _ in range(int(t)):
	n = input()
	n = int(n)
	l = list(map(int, input().split()))
	ma = max(l)
	l.remove(ma)
	sec = max(l)
	print(min(n - 2, sec - 1))


T = int(input())
for i in range(T):
	n = int(input())
	List = list(map(int, input().split()))
	List.sort()
	x = min(List[len(List) - 1], List[len(List) - 2])
	y = n - 2
	if y < 1 or x < 2:
		print(0)
	else:
		print(min(x - 1, y))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	a.reverse()
	b1 = a[0]
	b2 = a[1]
	t = 0
	for i in range(2, n + 1, 1):
		if b2 >= n - i + 1:
			print(n - i)
			break


t = int(input())
for item in range(t):
	a = int(input())
	b = sorted(list(map(int, input().split())))
	if a < 3:
		print(0)
	elif a >= b[-1]:
		print(min(b[-2] - 1, a - 2))
	elif a < b[-2]:
		print(a - 2)
	elif a > b[-2] and a < b[-1]:
		print(b[-2] - 1)


ii = lambda : int(input())
mi = lambda : map(int, input().split())
li = lambda : list(mi())
si = lambda : input()
for _ in range(ii()):
	n = ii()
	m = sorted(li())[-2]
	print(min(n - 2, m - 1))


t = int(input())
f = []
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a1 = max(a[0], a[1])
	a2 = min(a[0], a[1])
	for i in range(2, n):
		if a[i] >= a1:
			a2 = a1
			a1 = a[i]
		elif a[i] >= a2:
			a2 = a[i]
	f += [min(a2 - 1, n - 2)]
for i in f:
	print(i)


T = int(input())
for i in range(T):
	count = int(input())
	a = list(map(int, input().strip().split()))
	a.sort()
	if a[-1] != 1 and a[-2] != 1:
		if a[-2] - 1 >= count - 2:
			print(count - 2)
		elif a[-2] - 1 < count - 2:
			print(a[-2] - 1)
	else:
		print(0)


t = int(input())
k = 0
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))[:n]
	s = a[:]
	s.sort()
	k = s[-2] - 1
	if n - 2 >= k:
		print(k)
	elif n - 2 < k:
		print(n - 2)
	elif k <= 0:
		print(0)
	else:
		print(0)


t = int(input())
for q in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	a.sort()
	k1 = a[n - 1]
	k2 = a[n - 2]
	print(min(a[n - 2] - 1, n - 2))


def int_list():
	return [int(c) for c in input().split()]

def int1():
	return int(input())

def str_list():
	return [c for c in input().split()]

def str1():
	return input()
T = int1()
r = []
for _ in range(T):
	n = int1()
	p = int_list()
	p = sorted(p, reverse=True)
	max_k = p[1] if p[0] > p[1] else p[0]
	max_k -= 1
	k = n - 2
	res = k if k < max_k else max_k
	r.append(res)
for el in r:
	print(el)


n = int(input())

def cnt():
	input()
	length = [int(x) for x in input().split()]
	length.sort(reverse=True)
	(first_step, second_step) = (length[0], length[1])
	min_length = min(first_step, second_step) - 1
	length = length[2:]
	if min_length >= len(length):
		print(len(length))
	else:
		print(min_length)

def __main__(count):
	for x in range(count):
		cnt()
__main__(n)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(i) for i in input().split()]
	arr.sort()
	if n < 3 or min(arr[-1], arr[-2]) < 2:
		print(0)
	else:
		x = min(arr[-1], arr[-2])
		if n - 2 >= x:
			print(x - 1)
		else:
			print(n - 2)


t = int(input())
for _ in range(t):
	n = int(input())
	ls = list(sorted(list(map(int, input().split(' ')))))
	k = ls[-2] - 1
	k = min(k, n - 2)
	print(k)


def solve():
	n = int(input())
	a = sorted(list(map(int, input().split())))
	ans = min(a[-2] - 1, n - 2)
	print(ans)
t = int(input())
for _ in range(t):
	solve()


for i in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.remove(max(l))
	k = max(l)
	print(min(k - 1, n - 2))


for i in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	arr.sort()
	b1 = arr[n - 1]
	b2 = arr[n - 2]
	steps = n - 2
	while b1 < steps + 1 or b2 < steps + 1:
		steps -= 1
	if steps > 0:
		print(steps)
	else:
		print(0)


for TT in range(1, int(input()) + 1):
	n = int(input())
	l = sorted(map(int, input().split()))
	k = max(0, min(n - 2, l[-2] - 1))
	print(k)


import sys
from collections import defaultdict
import math

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = sorted(list(map(int, input().split())))
		print(min(a[-2] - 1, n - 2))
main()


T = int(input())
for i in range(1, T + 1):
	n = int(input())
	a = [int(s) for s in input().split()]
	k1 = max(a)
	del a[a.index(max(a))]
	k2 = max(a)
	del a[a.index(max(a))]
	if k1 > k2:
		length = k2 - 1
	else:
		length = k1 - 1
	if length == 0:
		print(0)
	elif len(a) <= length:
		print(len(a))
	else:
		print(length)


t = int(input())
for _ in range(t):
	n = int(input())
	nums = list(map(int, input().split()))
	nums.sort()
	(a, b) = (nums[-1], nums[-2])
	k_max = min(a, b) - 1
	if k_max == 0:
		print(0)
		continue
	if len(nums) - 2 >= k_max:
		print(k_max)
		continue
	else:
		print(len(nums) - 2)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	if n == 2:
		print(0)
		continue
	(m2, m1) = sorted(arr[:2])
	for a in arr[2:]:
		if a > m1:
			(m1, m2) = (a, m1)
		elif a > m2:
			m2 = a
	print(max(0, min(m2 - 1, n - 2)))


t = int(input())
for w in range(t):
	n = int(input())
	l = sorted([int(i) for i in input().split()])
	print(min(l[n - 2] - 1, n - 2))


T = int(input())
for k in range(T):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	if len(a) < 3:
		print(0)
	else:
		print(min(a[-2] - 1, n - 2))


class Read:

	@staticmethod
	def int():
		return int(input())

	@staticmethod
	def list(sep=' '):
		return input().split(sep)

	@staticmethod
	def list_int(sep=' '):
		return list(map(int, input().split(sep)))

def main():
	n = Read.int()
	a = Read.list_int()
	a.sort()
	h = min(a[-1], a[-2]) - 1
	res = min(h, n - 2)
	print(max(res, 0))
t = Read.int()
for j in range(t):
	main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	(max1, max2) = (-1, -1)
	for i in a:
		if i >= max1:
			(max1, max2) = (i, max1)
		else:
			max2 = max(max2, i)
	ans = min(n - 2, min(max1 - 1, max2 - 1))
	print(ans)


tc = int(input())
while tc != 0:
	tc -= 1
	n = int(input())
	ar = list(map(int, input().split()))
	if n == 2:
		print(0)
		continue
	(m1, m2, i1, i2) = (-1, -1, 0, 0)
	for i in range(n):
		if ar[i] >= m1:
			m2 = m1
			m1 = ar[i]
			i2 = i1
			i1 = i
		elif ar[i] > m2:
			m2 = ar[i]
			i2 = i
	if ar[i1] == 1 or ar[i2] == 1:
		print('0')
		continue
	cnt = 0
	for i in range(n):
		if i != i1 and i != i2:
			if ar[i] >= 1:
				cnt += 1
	print(min(cnt, min(m1, m2) - 1))


T = int(input())
for t in range(T):
	n = int(input())
	A = list(map(int, input().split()))
	A.sort(reverse=True)
	if len(A) < 3:
		print(0)
		continue
	ans = min(A[1] - 1, len(A) - 2)
	print(ans)


def co(l, n):
	count = 0
	for x in l:
		if x >= 1:
			pre = count
			count += 1
			if count >= n:
				return pre
	return count
for _ in range(int(input())):
	n = int(input())
	l = sorted(list(map(int, input().split())))
	k = l[-2] - 1
	s = co(l[:-2], l[-2])
	print(s)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	r = 0
	M = -1
	m = -1
	for b in a:
		if b >= 0:
			r += 1
		if b >= M:
			m = M
			M = b
		elif b >= m:
			m = b
	if (r - 2 > 0) * (m >= 2):
		print(min(r - 2, m - 1))
	else:
		print(0)


test = int(input())
for x in range(test):
	planks = int(input())
	drabina = list(map(int, input().split()))
	drabina.remove(max(drabina))
	max2 = max(drabina)
	drabina.remove(max(drabina))
	if max2 == 1:
		print(0)
	elif len(drabina) < max2:
		print(len(drabina))
	elif len(drabina) == max2:
		print(len(drabina) - 1)
	else:
		print(max2 - 1)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	x = a[-2]
	ans = 0
	for i in range(n - 2):
		if x > 1:
			ans += 1
			x -= 1
	print(ans)


a = int(input())
y = []
for i in range(a):
	b = int(input())
	x = list(map(int, input().split()))
	x.sort(reverse=True)
	if x[1] - 1 == 0 or b - 2 == 0:
		y.append(0)
	elif x[1] - 1 > b - 2:
		y.append(b - 2)
	else:
		y.append(x[1] - 1)
print(*y, sep='\n')


t = int(input())
for z in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort(reverse=True)
	(x, y) = (a[0], a[1])
	ans = y - 1
	ans = min(ans, len(a) - 2)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	p.sort()
	p.reverse()
	h = p[1]
	print(min(h - 1, n - 2))


t = int(input())
for i in range(t):
	p = int(input())
	l = list(map(int, input().split()))
	s = sorted(l, reverse=True)
	b = min(s[0], s[1])
	if b - 1 > p - 2:
		print(p - 2)
	else:
		print(b - 1)


import atexit
import io
import sys
R = lambda : map(int, input().split())
MAXC = int(100000.0)
for _ in range(int(input())):
	n = int(input())
	l = list(R())
	l.sort()
	print(min(l[-2] - 1, len(l) - 2), flush=True)


n = int(input())
for i in range(n):
	m = int(input())
	l = [int(x) for x in input().split()]
	l.sort()
	if m >= 3:
		k = m - 2
		while k >= 1:
			if l[m - 2] >= k + 1:
				print(k)
				break
			else:
				k -= 1
		else:
			print('0')
	else:
		print('0')


p = []
t = int(input())
for i in range(t):
	k = int(input())
	l = list(map(int, input().split()))
	l.sort(reverse=True)
	if len(l) <= 2:
		m = 0
		p.append(m)
	else:
		x = l[0]
		y = l[1]
		del l[0]
		del l[1]
		if len(l) >= x or len(l) >= y:
			m = y - 1
			p.append(m)
		else:
			m = len(l)
			p.append(m)
for g in range(len(p)):
	print(p[g])


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	ans = n - 2
	if n == 2:
		print(0)
	elif min(l[-1], l[-2]) - 1 >= ans:
		print(min((min(l[-1], l[-2]) - 1, ans)))
	elif min(l[-1], l[-2]) - 1 <= ans:
		print(min((min(l[-1], l[-2]) - 1, ans)))
	else:
		print(0)


for _ in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	arr.sort(reverse=True)
	ans = min(arr[0], arr[1]) - 1
	if n - 2 < ans:
		ans = n - 2
	print(ans)


R = lambda : map(int, input().split())
for _ in range(int(input())):
	n = int(input())
	arr = sorted(R(), reverse=True)
	print(min(arr[1] - 1, n - 2))


n = int(input())
for i in range(n):
	m = int(input())
	a = sorted(list(map(int, input().split())))
	if len(a) > 2:
		(b, d) = a[-2:]
		min1 = min(b, d)
		if min1 >= 2:
			print(min(len(a) - 2, min1 - 1))
			continue
	print(0)


Q = int(input())
for q in range(Q):
	n = int(input())
	P = list(map(int, input().split()))
	P.sort()
	k1 = P[-2]
	print(min([k1 - 1, n - 2]))


from sys import stdin, stdout
import collections
T = int(input())
for i in range(T):
	N = int(input())
	arr = [int(x) for x in stdin.readline().split()]
	arr.sort()
	ladder = arr[-2]
	ans = 0
	for i in range(N - 2):
		if ans == ladder - 1:
			break
		ans += 1
	print(ans)


queries = int(input())
info = []

def calcSteps(qtd_tabuas, lista_tamanho_tabuas):
	steps = 0
	if qtd_tabuas - 2 >= lista_tamanho_tabuas[-2]:
		steps = lista_tamanho_tabuas[-2] - 1
	else:
		steps = qtd_tabuas - 2
	print(steps)
while queries > 0:
	qtd_tabuas = int(input())
	lista_tamanho_tabuas = list(map(int, input().split()))
	lista_tamanho_tabuas.sort()
	info.append([qtd_tabuas, lista_tamanho_tabuas])
	queries -= 1
for i in info:
	if i[0] > 2:
		calcSteps(i[0], i[1])
	else:
		print(0)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	res = 0
	for i in range(1, n - 1):
		if i + 1 <= a[n - 2]:
			res = i
		else:
			break
	print(res)


for _ in range(int(input())):
	input()
	data = sorted(map(int, input().split()))[::-1]
	print(min(data[1] - 1, len(data) - 2))


t = int(input())
b = []
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ma = 0
	ma2 = 0
	for i in a:
		if i > ma:
			ma2 = ma
			ma = i
		elif i > ma2:
			ma2 = i
	n -= 2
	if ma2 == 1:
		b.append(0)
	elif ma2 - 1 >= n:
		b.append(n)
	else:
		b.append(ma2 - 1)
for i in range(t):
	print(b[i])


for i in range(int(input())):
	a = int(input())
	print(min(max(0, a - 2), sorted([int(x) for x in input().split()])[-2] - 1))


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split(' ')))
	l.sort(reverse=True)
	res = min(min(l[0] - 1, l[1] - 1), len(l) - 2)
	if res < 0:
		print('0')
	else:
		print(res)


queries = int(input())
final = []
for i in range(queries):
	temp = []
	n = int(input())
	length_of_l = [int(i) for i in input().split()]
	temp.append(n)
	temp.append(length_of_l)
	final.append(temp)
for query in final:
	a = query[1]
	a.sort(reverse=True)
	max_k = 0
	for max_k in range(len(a) - 1):
		if a[0] >= max_k + 1 and a[1] >= max_k + 1:
			continue
		else:
			max_k = max_k - 1
			break
	print(max_k)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	a.reverse()
	var1 = n - 2
	var2 = a[1] - 1
	ans = min(var1, var2)
	if ans < 1:
		print(0)
	else:
		print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	k = n - 2
	l1 = a[n - 1]
	l2 = a[n - 2]
	found = False
	while k > 0:
		x = min(l1, l2)
		if x >= k + 1:
			break
		else:
			k -= 1
	print(k)


R = lambda : map(int, input().split())
for _ in range(int(input())):
	n = int(input())
	L = sorted(R())
	ans = 0
	for i in range(n - 1):
		ans = min(L[i] - 1, i)
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	l = [int(i) for i in input().split()]
	l.sort()
	if l[-2] > n - 2:
		print(max(0, n - 2))
	else:
		print(l[-2] - 1)


def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		p = [int(x) for x in input().split()]
		p.sort()
		print(min(p[-2] - 1, len(p) - 2))
main()


T = int(input())
for i in range(T):
	n = int(input())
	l = list(map(int, input().split()))
	(max1, max2) = (0, 0)
	for i in range(n):
		x = l[i]
		if x >= max1:
			(max1, max2) = (x, max1)
		elif x > max2:
			max2 = x
	print(min(n - 2, min(max1, max2) - 1))


def solve():
	n = int(input())
	l = sorted(list(map(int, input().split())), reverse=True)
	k = n - 2
	print(min(k, l[1] - 1))
for _ in range(int(input())):
	solve()


import sys
import math
from collections import defaultdict
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	m1 = max(a)
	a.remove(m1)
	m2 = max(a)
	print(min(m2 - 1, n - 2))


t = int(input())
while t:
	n = int(input())
	arr = sorted(list(map(int, input().split())))
	print(min(min(arr[len(arr) - 1], arr[len(arr) - 2]) - 1, len(arr) - 2))
	t -= 1


t = int(input())

def binsearch(nums, target):
	left = 0
	right = len(nums) - 1
	while left <= right:
		mid = (left + right) // 2
		if nums[mid] == target:
			return mid
		elif nums[mid] > target:
			right = mid - 1
		elif nums[mid] < target:
			left = mid + 1
	return left
for tc in range(t):
	n = int(input())
	arr = [int(z) for z in input().split()]
	arr.sort()
	prelimk = arr[-2] - 1
	ans = 0
	for i in range(prelimk + 1):
		if binsearch(arr, i) <= n - 2 and n >= i + 2:
			ans = i
		else:
			break
	print(ans)


n = int(input())
for i in range(n):
	m = int(input())
	a = [int(x) for x in input().split()]
	b = sorted(a)
	print(min([len(b) - 2, b[-2] - 1]))


T = input()
for m in range(int(T)):
	n = input()
	a = input().split()
	max1 = 0
	max2 = 0
	for i in range(int(n)):
		if int(a[i]) >= max1:
			max2 = max1
			max1 = int(a[i])
		elif int(a[i]) > max2:
			max2 = int(a[i])
	if max2 > 1 and int(n) > 2:
		k = min(int(n) - 2, max2 - 1)
	else:
		k = 0
	print(k)


num = int(input())
for i in range(num):
	nobodycares = input()
	x = list(map(int, input().split()))
	x.sort()
	if len(x) - 2 < x[-2]:
		print(len(x) - 2)
	else:
		print(x[-2] - 1)


IN = input
rint = lambda : int(IN())
rmint = lambda : map(int, IN().split())
rlist = lambda : list(rmint())
t = rint()
for p in range(t):
	n = rint()
	a = rlist()
	a.sort()
	if n == 2 or a[-2] < 2:
		print(0)
	else:
		print(min(n - 2, a[-2] - 1))


from sys import stdin
c = int(stdin.readline().strip())
for i in range(c):
	n = int(stdin.readline().strip())
	s = list(map(int, stdin.readline().strip().split()))
	s.sort()
	l = min(s[-1], s[-2])
	ans = min(l - 1, n - 2)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = list((int(x) for x in input().split()))
	a.sort()
	a.pop()
	b = a.pop()
	print(min(b - 1, n - 2))


for _ in range(int(input())):
	n = int(input())
	a = [int(o) for o in input().split()]
	a = sorted(a)
	print(min(n - 2, a[-2] - 1))


t = int(input())
for _ in range(t):
	n = int(input())
	l = [int(x) for x in input().split()]
	l = sorted(l)
	i = 0
	b = min(l[-1], l[-2])
	a = n - 2
	print(min(a, b - 1))


import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
R = lambda : map(int, input().split())
MAXC = int(100000.0)
for _ in range(int(input())):
	n = int(input())
	l = list(R())
	l.sort()
	print(min(l[-2] - 1, len(l) - 2), flush=True)


t = int(input())
for i in range(t):
	n = int(input())
	var = list(map(int, input().split()))
	var.sort()
	if n == 2 or var[-2] < 2:
		print(0)
	else:
		print(min(min(var[-1], var[-2]) - 1, n - 2))


t = int(input())
for _ in range(t):
	n = int(input())
	A = [int(x) for x in input().split()]
	A.sort(reverse=True)
	k = A[1] - 1
	print(min(k, n - 2))


t = int(input())
while t > 0:
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort()
	i = n - 1
	k = a[i] - 1
	while i > 0 and k >= 0:
		if a[i - 1] >= k + 1 and i - 2 + 1 >= k and (a[0] >= 1):
			print(k)
			break
		else:
			k -= 1
	t -= 1


n = int(input().strip())
for i in range(n):
	planks = int(input().strip())
	planks_lst = sorted(map(int, input().split()))
	print(min(planks_lst[-2] - 1, planks - 2))


q = int(input())
for query in range(q):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	if len(l) < 3:
		print(0)
	else:
		a = l[-2]
		print(min(a - 1, len(l) - 2))


t = int(input(''))
for j in range(0, t):
	n = int(input(''))
	a = input('')
	l = []
	for i in a.split(' '):
		l.append(int(i))
	l.sort(reverse=True)
	s = l[1]
	if s > n - 2:
		print(n - 2)
	elif s - 1 > 0:
		print(s - 1)
	else:
		print('0')


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=1)
	k = min(a[:2]) - 1
	print(min(k, n - 2))


t = int(input())
for i in range(t):
	f = int(input())
	a = list(map(int, input().strip().split()))
	b = sorted(a)
	d = b[-2]
	print(min(f - 2, d - 1))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	k = min(a[n - 1], a[n - 2])
	if n - 2 >= k - 1:
		print(k - 1)
	elif n - 2 < k - 1:
		print(n - 2)


T = int(input())
b = []
for x in range(0, T):
	n = int(input())
	a = list(map(int, input().split()))
	if len(a) < 3:
		b.append(0)
		continue
	(max1, max2) = (max(a[0], a[1]), min(a[0], a[1]))
	for y in range(2, len(a)):
		if a[y] > max2:
			if a[y] > max1:
				max2 = max1
				max1 = a[y]
			else:
				max2 = a[y]
	b.append(min(max2 - 1, n - 2))
for x in b:
	print(x)


t = int(input())
while t > 0:
	d = int(input())
	n = list(map(int, input().split()))
	n = sorted(n)
	n = list(reversed(n))
	print(min(n[1] - 1, d - 2))
	t -= 1


t = int(input())
for tt in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	if n <= 2:
		print('0')
	else:
		a.sort()
		max_len = a[n - 2] - 1
		while max_len > 0 and n - 2 < max_len:
			max_len -= 1
		print(max_len)


T = int(input())
for _ in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	k = 0
	if len(a) >= 3:
		base1 = a[-1]
		base2 = a[-2]
		left_steps = n - 2
		k = min(base2 - 1, left_steps)
	print(k)


for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	m1 = max(a)
	a.remove(m1)
	m2 = max(a)
	s = m2 - 1
	if n == 2 or m2 < 2:
		print(0)
	elif n - 2 > s:
		print(s)
	else:
		print(n - 2)


def DIY_wooden_Ladder(a, n):
	a.sort()
	secondmax = a[n - 2]
	return min(secondmax - 1, n - 2)
t = int(input())
while t != 0:
	t = t - 1
	n = int(input())
	a = [int(i) for i in input().split()]
	print(DIY_wooden_Ladder(a, n))


q = int(input())
output = []
for i in range(q):
	n = int(input())
	planks = list(map(int, input().split()))
	planks.sort()
	steps = planks[-2] - 1
	temp = min(steps, n - 2)
	output.append(temp)
for i in output:
	print(i)


import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	N = int(input())
	A = sorted([int(a) for a in input().split()])
	print(min(A[-2] - 1, N - 2))


def solve_query(size, planks):
	if size <= 2:
		return 0
	(max1, max2) = (0, 0)
	for plank in planks:
		if plank >= max1:
			tmp = max1
			max1 = plank
			max2 = tmp
		elif plank >= max2:
			max2 = plank
	shorter_base = min(max1, max2)
	if shorter_base == 1:
		return 0
	return min(shorter_base - 1, size - 2)
n = int(input())
for case in range(0, n):
	dupa = input()
	planks = int(dupa)
	sizes_s = input()
	sizes_i = list(map(lambda c: int(c), sizes_s.split(' ')))
	print(solve_query(planks, sizes_i))


for i in range(int(input())):
	n = int(input())
	(*a, b, c) = sorted(map(int, input().split()))
	print(min(n - 2, b - 1))


from heapq import heappush, heappop
from collections import deque
import sys
sys.setrecursionlimit(10 ** 6)

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

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

def LI():
	return [int(i) for i in input().split()]

def bisect(ls, x):
	(l, r) = (0, len(ls))
	while r - l > 1:
		mid = (l + r) // 2
		if ls[mid] >= x:
			r = mid
		else:
			l = mid
	return l
q = I()
for _ in range(q):
	n = I()
	a = LI()
	a.sort()
	if a[-2] <= 1 or n <= 2:
		ans = 0
	else:
		ans = min(a[-2] - 1, n - 2)
	print(ans)


T = int(input())
for _ in range(T):
	n = int(input())
	a = [int(x) for x in input().split()]
	if n <= 2:
		print(0)
		continue
	a = sorted(a, reverse=True)
	l = a[1]
	k = min(l - 1, len(a) - 2)
	print(k)


T = int(input())
Q = []
for i in range(T):
	Q.append([])
	Q[-1].append(int(input()))
	Q[-1].append(list(map(int, input().strip().split())))
for i in Q:
	i[1].sort()
	A = i[1][-1]
	B = i[1][-2]
	if len(i[1]) - 2 + 1 <= B:
		print(len(i[1]) - 2)
	else:
		print(B - 1)


t = int(input())
n = 0
arr = []
res_arr = [0] * t
for i in range(t):
	n = int(input())
	tmp_arr = [int(el) for el in input().split()]
	arr.append(tmp_arr)
max_vals1 = [0] * t
max_vals2 = [0] * t
for i in range(t):
	max_vals1[i] = max(arr[i])
for i in range(t):
	for j in range(len(arr[i])):
		if arr[i][j] == max_vals1[i]:
			arr[i][j] = 0
			break
for i in range(t):
	max_vals2[i] = max(arr[i])
for i in range(t):
	res_arr[i] = max(arr[i])
	if len(arr[i]) == 2:
		print(0)
	else:
		print(min(len(arr[i]) - 2, max_vals2[i] - 1))


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split(' ')))
	arr.sort()
	k2 = arr[n - 2]
	cnt = 0
	for i in range(n - 2):
		cnt += int(arr[i] >= 1)
	print(min(cnt, k2 - 1))


t = int(input())
for m in range(t):
	n = int(input())
	lst = [int(x) for x in input().split()]
	lst.sort(reverse=True)
	count = 0
	for i in range(2, n):
		if count < lst[1] - 1:
			count += 1
	print(count)


from sys import stdin, stdout, exit
q = int(input())
for it in range(q):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	a.sort()
	l2 = a[-2]
	ans = min(n - 2, l2 - 1)
	stdout.write(str(ans) + '\n')


t = int(input())
ans = []
for x in range(t):
	n = int(input())
	planks = input().split(' ')
	long1 = 0
	long2 = 0
	for plank in planks:
		if int(plank) > long1:
			long2 = long1
			long1 = int(plank)
		elif int(plank) > long2:
			long2 = int(plank)
	seclongest = min(long1, long2)
	k = len(planks) - 2
	if seclongest >= k + 1:
		ans.append(k)
	else:
		ans.append(seclongest - 1)
for a in ans:
	print(a)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	r = a[-2]
	c = n - 2
	if r >= c + 1:
		print(c)
	else:
		print(r - 1)


def secmax(m):
	(fmax, smax) = (m[0], m[1])
	if fmax < smax:
		(fmax, smax) = (smax, fmax)
	for el in m[2:]:
		if el > smax:
			smax = el
			if fmax < smax:
				(fmax, smax) = (smax, fmax)
	return smax

def zap(n, a):
	b = secmax(a)
	print(min(b - 1, n - 2))
t = int(input())
for i in range(t):
	zap(int(input()), list(map(int, input().split())))


def search(a, k):
	kp1 = 0
	st = 0
	for i in a:
		if i >= k + 1 and kp1 < 2:
			kp1 += 1
		else:
			st += 1
	return st >= k and kp1 == 2
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	l = 0
	r = int(10000000.0)
	ans = 0
	while l <= r:
		mid = (r + l) // 2
		if search(a, mid):
			ans = mid
			l = mid + 1
		else:
			r = mid - 1
	print(ans)


from sys import stdin
N = int(stdin.readline().rstrip())
for _ in range(N):
	n = int(stdin.readline().rstrip())
	data = [int(x) for x in stdin.readline().rstrip().split()]
	s = sorted(data)[-2]
	if s == 1:
		print(0)
	elif n == 0:
		print(0)
	else:
		print(min(n - 2, s - 1))


import sys
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, sys.stdin.readline().split()))
	a.sort(reverse=True)
	k = max(0, min(n - 2, a[1] - 1))
	print(k)


numofquerys = int(input())
n = []
a = []
counter = 0
for i in range(numofquerys):
	n.append(input())
	a.append(input().split())
for i in range(len(n)):
	for j in range(len(a[i])):
		a[i][j] = int(a[i][j])
for i in range(len(n)):
	threshold = int(n[i]) - 2
	a[i].sort(reverse=True)
	lowestnum = a[i][1]
	if lowestnum == int(n[i]):
		k = lowestnum - 2
	else:
		k = lowestnum - 1
	if k > int(n[i]) - 2:
		k = int(n[i]) - 2
	print(k)


import sys

def main():
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	print(min(n - 2, a[-2] - 1))
	return

def test():
	t = int(input())
	while t:
		main()
		t -= 1
test()


for i in range(int(input())):
	(k, l) = (int(input()), sorted(map(int, input().split())))
	h = min(l[-1], l[-2]) - 1
	print(min(h, k - 2))


for i in range(int(input())):
	n = int(input())
	l = input().split()
	a = b = 0
	for x in l:
		if int(x) >= a:
			b = a
			a = int(x)
		elif b <= int(x) < a:
			b = int(x)
	if b > 1:
		print(min(b - 1, n - 2))
	else:
		print(0)


import heapq
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	if n <= 2:
		print(0)
		continue
	largest = heapq.nlargest(2, arr)
	if largest[1] < largest[0]:
		(largest[0], largest[1]) = (largest[1], largest[0])
	if largest[0] <= 1:
		print(0)
		continue
	step = largest[0] - 1
	if len(arr) - 2 >= step:
		print(step)
	else:
		print(len(arr) - 2)


x = int(input())
for i in range(x):
	n = int(input())
	p = list(map(int, input().split()))
	p.sort()
	cont = len(p) - 2
	minimo = min(p[-1], p[-2]) - 1
	if minimo == cont:
		print(minimo)
	elif minimo > cont:
		print(cont)
	else:
		print(minimo)


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort()
	print(max(min(len(a) - 2, a[-2] - 1), 0))


import collections
import math
t = int(input())
for q in range(0, t):
	n = int(input())
	a = [int(i) for i in input().split()]
	d = collections.Counter(a)
	a = sorted(a, reverse=True)
	ans = a[0] - 1
	while (ans >= a[0] or ans >= a[1] or ans > n - 2) and ans != 0:
		ans -= 1
	print(ans)


def check(a, k):
	if a[-2] < k + 1:
		return False
	return len(a) - 2 >= k

def handle():
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort()
	le = 0
	ri = n
	while ri - le > 1:
		mid = (le + ri) // 2
		if check(a, mid):
			le = mid
		else:
			ri = mid
	print(le)
t = int(input())
for i in range(t):
	handle()


def solve():
	t = int(input())
	for i in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		temp = sorted(a)
		ans = temp[n - 2] - 1
		if ans > n - 2:
			ans = n - 2
		print(ans)
solve()


import sys
import math
import bisect

def solve(A):
	n = len(A)
	A.sort()
	h = A[-2]
	return min(n - 2, h - 1)

def main():
	for _ in range(int(input())):
		n = int(input())
		A = list(map(int, input().split()))
		print(solve(A))
main()


import sys
n = int(sys.stdin.readline())
for i in range(n):
	plank_no = int(sys.stdin.readline())
	planks = sys.stdin.readline().split()
	planks = [int(x) for x in planks]
	largest = 0
	second_largest = 0
	for x in planks:
		if x >= second_largest:
			if x > largest:
				second_largest = largest
				largest = x
			else:
				second_largest = x
	if second_largest - 1 > plank_no - 2:
		print(plank_no - 2)
	else:
		print(second_largest - 1)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	x = a[-2]
	y = len(a[:n - 2])
	if y >= x:
		print(x - 1)
	else:
		print(y)


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

def getN():
	return int(input())

def getList():
	return list(map(int, input().split()))
import math

def solve():
	n = getN()
	nums = getList()
	nums.sort()
	mx = nums[-2]
	print(min(mx - 1, n - 2))
t = getN()
for times in range(t):
	solve()


mod = 1000000007
mod1 = 998244353
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
t = ii()
for i in range(t):
	n = ii()
	l = sorted(il())
	if n == 2:
		print(0)
	elif n - 2 > 0:
		print(min(l[-2] - 1, n - 2))


q = int(input())
for i in range(q):
	n = int(input())
	a = sorted([int(i) for i in input().split()])
	print(min(min(a[-1], a[-2]) - 1, n - 2))


q = int(input())
for i in range(q):
	n = int(input())
	boards = list(map(int, input().split()))
	boards.sort()
	length = min(boards[n - 1], boards[n - 2])
	count = 0
	for i in range(n - 2):
		if boards[i] > 0:
			count += 1
	print(min(length - 1, count))


import sys
t = int(sys.stdin.readline())
for query in range(t):
	n = int(sys.stdin.readline())
	a = [int(x) for x in sys.stdin.readline().strip().split()]
	a.sort()
	ans = 0
	if n > 2 and a[-2] > 1:
		ans = min(a[-2] - 1, n - 2)
	print(ans)


import sys
import math as mt
import bisect
input = sys.stdin.readline
t = int(input())

def ncr_util():
	inv[0] = inv[1] = 1
	fact[0] = fact[1] = 1
	for i in range(2, 300001):
		inv[i] = inv[i % p] * (p - p // i) % p
	for i in range(1, 300001):
		inv[i] = inv[i - 1] * inv[i] % p
		fact[i] = fact[i - 1] * i % p

def solve():
	mini = min(l[0], l[1])
	n1 = n - 2
	return max(min(n1, mini - 1), 0)
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort(reverse=True)
	print(solve())


T = int(input())
for t in range(T):
	N = int(input())
	Arr = list(map(int, input().split()))
	Arr.sort(reverse=True)
	M = min(Arr[0], Arr[1])
	if len(Arr) == 1 or M - 1 == 0:
		print(0)
	else:
		print(min(len(Arr) - 2, M - 1))


t = int(input())
for _ in range(t):
	n = int(input())
	l = sorted(map(int, input().split()))
	if n < 3:
		print(0)
		continue
	print(min(n - 2, l[-2] - 1))


import heapq
for t in range(int(input())):
	n = int(input())
	a_values = list(map(int, input().split()))
	largest_2 = heapq.nlargest(2, a_values)
	print(min(min(largest_2) - 1, n - 2))


t = int(input())
while t:
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	print(min(a[n - 2] - 1, n - 2))
	t -= 1


l = int(input())
while l:
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	n -= 2
	print(min(n, a[1] - 1))
	l -= 1


for _ in range(int(input(''))):
	t = int(input(''))
	a = list(map(int, input().split()))
	a.sort()
	f = a[-1]
	s = a[-2]
	if t <= 2:
		print('0')
		continue
	del a[-1]
	del a[-1]
	print(min(t - 2, s - 1))


for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	lis.sort()
	x = min(lis[-1], lis[-2])
	lis.pop()
	lis.pop()
	print(min(x - 1, len(lis)))


T = int(input())
for _ in range(T):
	n = int(input())
	boards = list(map(int, input().split()))
	boards.sort(reverse=True)
	size = min(boards[1] - 1, n - 2)
	if size < 0:
		size = 0
	print(size)


from sys import stdin

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

def r_t(tp):
	return map(tp, r().split())

def r_a(tp):
	return list(r_t(tp))

def main():
	global r
	cases = int(stdin.readline())
	for case in range(cases):
		n = int(stdin.readline())
		A = list(map(int, stdin.readline().strip().split()))
		A.sort()
		print(min(A[-2] - 1, n - 2))
main()


n = int(input())
for i in range(0, n):
	k = int(input())
	S = list(map(int, input().split()))
	max1 = S[0]
	max2 = S[1]
	for j in range(2, len(S)):
		if S[j] > max1:
			if max2 > max1:
				max1 = S[j]
			else:
				max2 = S[j]
		elif S[j] > max2:
			if max1 > max2:
				max2 = S[j]
			else:
				max1 = S[j]
	ans = 0
	A = [max1, max2]
	ch = min(A)
	if len(S) - 2 <= ch - 1:
		ans = len(S) - 2
	else:
		ans = ch - 1
	print(ans)


T = int(input())
for t in range(0, T):
	N = int(input())
	if N == 0:
		print(0)
	else:
		A = input().split()
		A = map(int, A)
		A = list(A)
		A.sort()
		S = A[N - 2]
		for a in A:
			if a == 0:
				S -= 1
		S -= 1
		if N - 2 < S:
			S = N - 2
		if S <= 0:
			S = 0
		print(S)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a = sorted(a, reverse=True)
	height = min(a[0], a[1]) - 1
	print(min(height, len(a) - 2))


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	count = 0
	n = len(arr)
	if len(arr) < 3 or arr[-2] == 1:
		print(0)
	else:
		for i in range(len(arr)):
			if arr[i] != 1:
				count += 1
		if count != len(arr):
			arr = arr[count - 1:]
		maxlen = arr[-2] - 1
		if n - 2 >= maxlen:
			print(maxlen)
		else:
			print(max(n - 2, 0))


t = int(input())
for i in range(t):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	s = 0
	for j in range(n - 1):
		if a[j] > j:
			s = j
		elif a[j] - 1 <= j:
			s = a[j] - 1
	print(s)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	second = a[-2]
	a.remove(a[-1])
	a.remove(a[-1])
	print(min(len(a), second - 1))


t = int(input())
while t:
	n = int(input())
	l = [int(i) for i in input().split(' ')]
	l.sort(reverse=True)
	i = 0
	j = 1
	k = 2
	while k <= n - 1:
		pre = len(l) - k + 1
		if pre <= l[i] and pre <= l[j]:
			print(len(l) - k)
			break
		else:
			k = k + 1
	else:
		print(0)
	t = t - 1


def check():
	n = int(input())
	a = list(map(int, input().split()))
	if n == 2:
		print(0)
		return
	m1 = -1
	m2 = -1
	for i in range(n):
		if a[i] >= m1:
			m2 = m1
			m1 = a[i]
		elif a[i] > m2:
			m2 = a[i]
	print(min(m2 - 1, m1 - 1, n - 2))
for _ in range(int(input())):
	check()


def readn():
	return int(input())

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

def readnos():
	return map(int, input().split())
for _ in range(readn()):
	n = int(input())
	a = readlist()
	a.sort()
	m = min(a[n - 2], a[n - 1])
	if m == 1 or n == 2:
		print(0)
	else:
		maxx = m - 1
		if n - 2 < maxx:
			print(n - 2)
		else:
			print(maxx)


T = int(input())
for _ in range(0, T):
	N = int(input())
	s = [int(x) for x in input().split()]
	s.sort()
	if len(s) < 3:
		print(0)
	elif min(s[-1], s[-2]) < 2:
		print(0)
	else:
		base = min(s[-1], s[-2]) - 1
		ans = min(base, len(s) - 2)
		print(ans)


queries = int(input())
for _ in range(queries):
	_ = int(input())
	planks = list(map(int, input().split()))
	planks.remove(max(planks))
	biggest = max(planks)
	planks.remove(max(planks))
	print(min(len(planks), biggest - 1))


T = int(input())
for kase in range(T):
	n = int(input())
	lis = [int(x) for x in input().split()]
	lis.sort()
	print(min(n - 2, lis[-2] - 1))


t = int(input())
for _ in range(t):
	n = int(input())
	max_a = -float('inf')
	max_b = -float('inf')
	for l in map(int, input().split()):
		if max_a == max_b and l > max_a:
			max_a = l
		elif max_a > max_b and l > max_b:
			max_b = l
		elif max_b > max_a and l > max_a:
			max_a = l
	print(min(min(max_a, max_b) - 1, n - 2))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a = sorted(a, reverse=True, key=int)
	(b, c) = (a[0], a[1])
	a.remove(a[0])
	a.remove(a[0])
	k = 0
	if b != c:
		k = len(a)
		print(k if k < c else c - 1)
	else:
		k = len(a)
		print(k if k < c else c - 1)


requests = int(input())
answers = []
for i in range(requests):
	numberOfPlates = int(input())
	fakeLengthOfPlates = input().split()
	lengthOfPlates = []
	for i in fakeLengthOfPlates:
		lengthOfPlates.append(int(i))
	lengthOfPlates = sorted(lengthOfPlates, reverse=True)
	if numberOfPlates < 3:
		answers.append(0)
		continue
	else:
		a = lengthOfPlates[0] - 1
		b = lengthOfPlates[1] - 1
		answer = 0
		for i in range(2, numberOfPlates + 1):
			if a == 0 or b == 0 or i == numberOfPlates:
				answers.append(answer)
				break
			else:
				a -= 1
				b -= 1
				answer += 1
for i in answers:
	print(i)


t = int(input())
for tc in range(t):
	n = int(input())
	l = [int(i) for i in input().split()]
	if len(l) < 3:
		print(0)
	else:
		l.sort(reverse=True)
		a = l[0]
		b = l[1]
		ch = min(a, b)
		rem = len(l) - 2
		k = min(rem, ch - 1)
		if ch < k + 1:
			k = 0
		print(k)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	j = len(a)
	k = n - 2
	while True:
		if a[-1] >= k + 1 and a[-2] >= k + 1:
			break
		k = k - 1
	print(k)


cs = int(input())
for c in range(cs):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort(reverse=True)
	se_mx = l[1]
	if l[1] == 1:
		print(0)
	else:
		print(min(se_mx - 1, n - 2))


t = int(input())
arr = []
for i in range(t):
	k = int(input())
	x = [int(j) for j in input().split()]
	arr.append(x)
for i in range(t):
	arr[i].sort(reverse=True)
	print(min(len(arr[i]) - 2, arr[i][1] - 1))


from collections import deque

def find_step(n, a):
	a.sort(reverse=True)
	a = deque(a)
	f1 = a.popleft() - 1
	f2 = a.popleft() - 1
	k = 0
	while f1 > 0 and f2 > 0 and a:
		if a.pop() >= 1:
			f1 -= 1
			f2 -= 1
			k += 1
	return k
for _ in range(int(input())):
	n = int(input().strip())
	a = list(map(int, input().strip().split()))
	print(find_step(n, a))


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort()
	count = 0
	m = min(a[len(a) - 1], a[len(a) - 2])
	k = m - 1
	if len(a) - 2 >= k:
		print(k)
	elif a[len(a) - 1] < 2 or a[len(a) - 2] < 2:
		print(0)
	elif len(a) - 2 < k:
		print(len(a) - 2)
	else:
		print(0)


T = int(input())
for t in range(T):
	n = int(input())
	arr = sorted(list(map(int, input().split())))
	if n == 2:
		print(0)
	else:
		ans = 0
		for i in range(1, n - 1):
			if arr[n - 1] >= i + 1 and arr[n - 2] >= i + 1:
				ans = i
		print(ans)


n = int(input())
for i in range(0, n):
	o = int(input())
	p = input().rstrip().split(' ')
	if 1:
		p.sort(key=int)
		x = list(set(p))
		x.sort(key=int, reverse=True)
		for j in range(len(p) - 2, 0, -1):
			A = j
			B = -1
			I = 0
			J = len(p) - 1
			while I <= J:
				m = (I + J) // 2
				if int(p[m]) >= j + 1:
					B = m
					J = m - 1
				else:
					I = m + 1
			if B != -1:
				C = len(p) - B
				if C >= 2:
					print(A)
					break
		else:
			print(0)


T = int(input())
ans = []
for i in range(T):
	maxi = 0
	num = int(input())
	planks = list(map(int, input().split()))
	planks[planks.index(max(planks))] = 0
	maxi = max(planks)
	ans.append(min(maxi - 1, num - 2))
for i in ans:
	print(i if i >= 0 else 0)


t = int(input())
for _ in range(t):
	n = int(input())
	mini = 1000000000
	arr = list(map(int, input().split()))
	a = max(arr)
	c = arr.count(a)
	if n == 2:
		print(0)
	elif c > 1:
		print(min(a - 1, n - 2))
	else:
		maxi = 0
		for i in range(n):
			if maxi < arr[i] and arr[i] != a:
				maxi = arr[i]
		print(min(maxi - 1, n - 2))


t = int(input())
for w in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	a.sort(reverse=True)
	print(min(a[1] - 1, n - 2))


n = int(input())
for i in range(n):
	t = int(input())
	a = [int(x) for x in input().split()]
	m1 = max(a)
	a[a.index(m1)] = -1
	m2 = max(a)
	print(t - 2 - max(t - 1 - min(m1, m2), 0))


for q in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	m = l[-2] - 1
	print(min(m, n - 2))


t = int(input())
for _ in range(t):
	n = int(input())
	a = sorted(map(int, input().split()))
	if n < 3 or a[n - 2] < 2:
		print(0)
	else:
		print(min(a[n - 2] - 1, n - 2))


def f(i):
	(n, A) = i
	A.sort()
	max_len = A[n - 1]
	sec_max_len = A[n - 2]
	res = min(sec_max_len - 1, n - 2)
	return res
l = []
for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	l.append([n, A])
ans = [f(i) for i in l]
for i in ans:
	print(i)


t = int(input())
while t:
	t -= 1
	n = int(input())
	l = [int(x) for x in input().split(' ')]
	l.sort(reverse=True)
	print(min(l[1] - 1, n - 2))


queries = int(input())
for _ in range(queries):
	planks = int(input())
	lenghts = [int(x) for x in input().split()]
	lenghts.sort()
	k = min(planks - 2, lenghts[-2] - 1)
	print(k)


t = int(input())
for f in range(t):
	n = int(input())
	x = list(map(int, input().split()))
	(max1, max2) = (0, 0)
	for i in range(n):
		if x[i] >= max1:
			max2 = max1
			max1 = x[i]
		elif x[i] >= max2:
			max2 = x[i]
	if n - 2 > 0 and max2 > 1:
		if n - 2 < max2:
			print(n - 2)
		else:
			print(max2 - 1)
	else:
		print(0)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split(' ')))
	a.sort()
	x = min(a[-1], a[-2]) - 1
	y = n - 2
	print(min(x, y))


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	c = arr[-1]
	d = arr[-2]
	k = 0
	rem = n - 2
	if rem <= d - 1:
		print(rem)
	elif rem > d - 1:
		print(d - 1)
	else:
		print(0)


t = int(input())
for i in range(t):
	n = int(input())
	numbers = list(map(int, input().split()))
	high = max(numbers)
	numbers.remove(high)
	high = max(numbers)
	numbers.remove(high)
	length = len(numbers)
	if length < high:
		print(length)
	elif length >= high:
		print(high - 1)


for _ in range(int(input())):
	n = int(input())
	A = [int(i) for i in input().split()]
	A.sort(reverse=True)
	if len(A) >= 2:
		k = A[1] - 1
		if k <= n - 2:
			print(k)
		else:
			print(n - 2)


t = int(input())
while t > 0:
	ans = 0
	n = int(input())
	arr = [int(x) for x in input().split()]
	arr.sort()
	print(min(n - 2, min(arr[-1], arr[-2]) - 1))
	t -= 1


test = int(input())
for _ in range(test):
	n = int(input())
	ls1 = list(map(int, input().split()))
	ls1.sort(reverse=True)
	r = min(ls1[1], ls1[0]) - 1
	if r < n - 2:
		print(str(r))
	else:
		print(str(n - 2))


t = int(input())
for _ in range(t):
	n = int(input())
	lst = list(map(int, input().strip().split()))
	lst = sorted(lst)
	b = min(lst[n - 1], lst[n - 2])
	l = min(n - 2, b - 1)
	print(l)


T = int(input())
for _ in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	base = [a.pop(), a.pop()]
	kmustbe = min(base) - 1
	step = min(kmustbe, len(a))
	print(step)


no_q = int(input())
for i in range(no_q):
	n = int(input())
	list1 = [*map(int, input().split())]
	list1.sort()
	m = list1[-2] - 1
	if min(n - 2, m) >= 0:
		print(min(n - 2, m))
	else:
		print('0')


N = int(input())
for s in range(N):
	n = int(input())
	a = list(map(int, input().split()))
	if n < 3:
		print(0)
	else:
		a.sort()
		if a[-1] > 1 and a[-2] > 1:
			print(min(a[-2] - 1, n - 2))
		else:
			print(0)


import sys
input = lambda : sys.stdin.readline().strip()
T = int(input())
for i in range(T):
	n = int(input())
	ls = list(map(int, input().split()))
	ls.sort(reverse=True)
	print(min(min(ls[0], ls[1]) - 1, n - 2))


import math
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	b.extend(a)
	a.sort()
	b.sort(reverse=True)
	c = b[0]
	d = b[1]
	print(min(d - 1, n - 2))


T = int(input())
for i in range(T):
	n = int(input())
	a = map(int, input().split())
	a = sorted(a, reverse=True)
	k = 0
	for j in range(2, n):
		if k == a[1] - 1:
			break
		k += 1
	print(k)


q = int(input())
for i in range(q):
	n = int(input())
	A = list(map(int, input().split()))
	m1 = 0
	m2 = 0
	for j in range(n):
		if A[j] >= m1:
			m2 = m1
			m1 = A[j]
		elif A[j] > m2:
			m2 = A[j]
	if m2 == 1 or n - 2 == 0:
		print(0)
	else:
		print(min(m2 - 1, n - 2))


for i in range(int(input())):
	n = int(input())
	a = [int(a) for a in input().split()]
	a.sort()
	step = 1
	cnt = 0
	for j in range(n - 2):
		if step < a[-2]:
			cnt += 1
			step += 1
		else:
			break
	print(cnt)


mod = 10 ** 9 + 7
from sys import stdin, stdout
import bisect
from bisect import bisect_left as bl
from bisect import bisect_right as br
import itertools
import collections
import math
import heapq
from random import randint as rn

def modinv(n, p):
	return pow(n, p - 2, p)

def ncr(n, r, p):
	t = fact[n] * (ifact[r] * ifact[n - r] % p) % p
	return t

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())

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

def GCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def main():
	t = inin()
	for _ in range(t):
		n = inin()
		l = ain()
		j = max(l)
		l.pop(l.index(j))
		j = max(l) - 1
		n = n - 2
		if n < j:
			print(n)
		else:
			print(j)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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()


nq = int(input())
for i in range(nq):
	n = int(input())
	ladders = [int(i) for i in input().split(' ')]
	ladders.sort()
	min_base = ladders[-2]
	max_base = ladders[-1]
	if max_base > 1:
		count = min(len(ladders) - 2, min_base - 1)
		print(count)
	else:
		print(0)


test_cases = int(input())

def solve(n, legs):
	if n <= 2:
		return 0
	[mm, m] = sorted(legs[:2])
	for item in legs[2:]:
		if item > m:
			mm = m
			m = item
		elif item > mm:
			mm = item
	return min(mm - 1, n - 2)
while test_cases:
	print(solve(int(input()), [int(item) for item in input().split(' ')]))
	test_cases -= 1


t = int(input())
for i in range(t):
	n = int(input())
	g = list(map(int, input().split()))
	m1 = max(g)
	g.remove(m1)
	m2 = max(g)
	dl = len(g) - 1
	print(min(dl, m2 - 1))


T = int(input())
for _ in range(T):
	n = int(input())
	doski = map(int, input().split())
	doski = sorted(doski)
	print(min(doski[-2] - 1, n - 2))


def main():

	def solve():
		n = int(input())
		arr = sorted(map(int, input().split()))
		a = arr[-2]
		print(min(n - 2, a - 1))
	import sys
	input = sys.stdin.readline
	for _ in range(int(input())):
		solve()
	return 0
main()


n_requests = int(input())

def search_m(d):
	d_max_1 = max(d)
	d.remove(d_max_1)
	d_max_2 = max(d)
	d.remove(d_max_2)
	if len(d) > d_max_2 - 1:
		return d_max_2 - 1
	else:
		return len(d)
for i in range(n_requests):
	n_dosok = int(input())
	list_dosok = [int(i) for i in input().split()]
	list_dosok.sort(reverse=True)
	print(search_m(list_dosok))

def pv(a):
	for i in range(2, len(a)):
		if a[1] >= a[i]:
			if a[1] < len(a[i:]):
				return a[1] - 1
			else:
				return len(a[i:])
	return 0


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	k1 = a[-2]
	num_max_tabuas = k1 - 1
	if num_max_tabuas == 0:
		print(0)
	else:
		print(min(len(a) - 2, num_max_tabuas))


R = lambda : map(int, input().split())
for i in range(int(input())):
	n = int(input())
	planks = sorted(R())
	steps = 0
	maxiStep = planks[-2] - 1
	for j in range(n - 3, -1, -1):
		if planks[j] <= planks[-2] and steps < maxiStep:
			steps += 1
	print(steps)


t = int(input())
result = []
for i in range(t):
	n = input()
	nums = [int(i) for i in input().split()]
	max1 = max(nums)
	nums.remove(max1)
	max2 = max(nums)
	nums.remove(max2)
	if max2 >= len(nums) + 1:
		result.append(len(nums))
	else:
		result.append(max2 - 1)
for i in result:
	print(i)


t = int(input())
s = []
for njf in range(0, t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	h = min(a[n - 1], a[n - 2])
	h -= 1
	s.append(min(h, n - 2))
for i in s:
	print(i)


t = int(input())
while t:
	t -= 1
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	print(min(l[-2] - 1, len(l) - 2))


t = int(input())
for i in range(0, t):
	n = int(input())
	a = [int(i) for i in input().split()]
	a.sort()
	s = a[n - 2]
	print(min(s - 1, n - 2))


T = int(input())
for t in range(T):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	m0 = arr[-1]
	m1 = arr[-2]
	if m1 == 1 or m0 == 1:
		print(0)
	else:
		print(min(len(arr) - 2, m1 - 1))


for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	lis.sort()
	k = lis[-2] - 1
	print(k) if k <= n - 2 else print(n - 2)


def main():
	T = int(input())
	for _ in range(T):
		n = int(input())
		a = [int(s) for s in input().split()]
		a.sort()
		print(min(a[-2] - 1, n - 2))
main()


t = int(input())
for _ in range(t):
	n = input()
	a = list(map(int, input().split()))
	a.sort()
	k_step = len(a) - 2
	check = a[-2]
	if check > k_step:
		print(k_step)
	else:
		while check <= k_step:
			k_step -= 1
			check = a[-2]
		print(k_step)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split(' ')]
	a.sort()
	maxK = a[-2] - 1
	ans = min(maxK, len(a) - 2)
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	ar = list(map(int, input().split()))
	if n < 3:
		print('0')
		continue
	ar = sorted(ar)
	ar.reverse()
	print(min(ar[1] - 1, n - 2))


t = int(input())
for i in range(t):
	n = int(input())
	planks = sorted([int(k) for k in input().split()], reverse=True)
	while planks[0] < len(planks) - 1 or planks[1] < len(planks) - 1:
		planks.pop()
	print(len(planks) - 2)


T = int(input())
result = []
for i in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	if n == 2:
		result.append(0)
	elif a[-2] > len(a) - 2:
		result.append(len(a) - 2)
	else:
		result.append(a[-2] - 1)
for j in range(len(result)):
	print(result[j])


T = int(input())
for _ in range(T):
	n = int(input())
	L = [int(x) for x in input().split()]
	L.sort()
	if L[-2] >= n - 1:
		print(n - 2)
	else:
		print(L[-2] - 1)


T = int(input())
for _ in range(0, T):
	n = int(input())
	a = list(map(int, input().split()))
	maxi = [0, 0]
	for i in range(0, n):
		if maxi[0] < a[i]:
			maxi[0] = a[i]
	a.remove(maxi[0])
	for i in range(0, n - 1):
		if maxi[1] < a[i]:
			maxi[1] = a[i]
	if maxi[1] < n - 1:
		if maxi[0] > maxi[1]:
			print(maxi[1] - 1)
		else:
			print(maxi[0] - 1)
	else:
		print(n - 2)


for i in range(int(input())):
	k = int(input())
	arr = sorted([int(x) for x in input().split(' ')])
	print(min(arr[k - 2] - 1, k - 2))


def get_base(l):
	return (l[-1], l[-2])

def get_max_steps(l):
	l.sort()
	k = 0
	while len(l) >= 3:
		(a, b) = get_base(l)
		l.remove(a)
		l.remove(b)
		not_used = []
		for i in l:
			if k + 1 < min(a, b):
				k += 1
			else:
				not_used.append(i)
		l = not_used
		if len(not_used) == len(l):
			break
	return k
n = int(input())
for _ in range(n):
	t = input()
	lengths = list(map(int, input().split()))
	print(get_max_steps(lengths))


a = int(input())
for i in range(a):
	c = int(input())
	b = list(map(int, input().split()))
	b.sort()
	if c <= 2:
		print(0)
		continue
	maxx = b[-2]
	print(min(maxx - 1, c - 2))


k = int(input())
i = 0
while i < k:
	a = int(input())
	b = list(map(int, input().split(' ')))
	b.sort(reverse=True)
	base1 = b[0]
	base2 = b[1]
	ans = 0
	index = 2
	while index < len(b) and ans <= base2 + 2 and (b[index] > base2):
		ans = ans + 1
		index = index + 1
	print(min(len(b) - 2 - ans, base2 - 1))
	i = i + 1


t = input()
t = int(t)
s = []
for i in range(0, t, 1):
	n = input()
	n = int(n)
	l = list(map(int, input().strip().split()))
	m = max(l)
	l.remove(m)
	p = max(l)
	if p < n - 1:
		s.append(p - 1)
	else:
		s.append(n - 2)
for i in range(0, t, 1):
	print(f'{s[i]}')


def solve():
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for i in a:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	k = -1
	p = list(d.keys())
	h = max(p)
	c = 0
	if d[h] >= 2:
		z = h
		c = d[h] - 2
		p[p.index(h)] = -1
		for i in p:
			if i == -1:
				continue
			c += d[i]
	if d[h] == 1:
		p[p.index(h)] = -1
		h = max(p)
		z = h
		c += d[h] - 1
		p[p.index(h)] = -1
		for i in p:
			if i == -1:
				continue
			c += d[i]
	print(min(z - 1, c))

def main():
	t = 1
	if t == 0:
		test = 1
	else:
		test = int(input())
	for _ in range(test):
		solve()
main()


import sys
sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	N = int(input())
	L = list(map(int, input().split()))
	L = list(filter(lambda x: x >= 1, L))
	L = sorted(L)
	base_len = L[-2] - 1
	ladder_num = len(L) - 2
	print(min(base_len, ladder_num))


t = int(input())
while t:
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	a1 = a[1] - 1
	a2 = n - 2
	ans = min(a1, a2)
	print(ans)
	t -= 1


t = int(input())
for i in range(t):
	k = 0
	m = 0
	n = int(input())
	a = [int(n) for n in input().split(' ')]
	a = sorted(a)
	a = a[::-1]
	m = a[1] - 1
	print(min(n - 2, m))


consultas = int(input())
resultados = []
for i in range(consultas):
	madeiras = int(input())
	comprimentos = [int(v) for v in input().split()]
	comprimentos.sort()
	menorT = int(comprimentos[len(comprimentos) - 2]) - 1
	if len(comprimentos) - 2 >= menorT:
		resultados.append(menorT)
	elif len(comprimentos) - 2 < menorT:
		resultados.append(len(comprimentos) - 2)
for i in range(len(resultados)):
	print(resultados[i])


t = int(input())
ans = []
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	len1 = len(a) - 2
	len2 = a[-2] - 1
	ans.append(min(len1, len2))
print(*ans, sep='\n')


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	if n > 2:
		c = min(n - 2, a[-2] - 1)
	else:
		c = 0
	print(c)


t = int(input())
ans = []
for x in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a = sorted(a)
	(b1, b2) = (a[-1], a[-2])
	if b1 > b2:
		steps = b2 - 1
	else:
		steps = b1 - 1
	a.pop(-1)
	a.pop(-1)
	a = [y for y in a if y >= 1]
	if steps > len(a):
		ans.append(len(a))
	else:
		ans.append(steps)
for y in ans:
	print(y)


def maxlen(a, b, c):
	a = a - 2
	if b == 1 or c == 1:
		return 0
	else:
		b = b - 1
		c = c - 1
		if a <= b and a <= c:
			return a
		elif b < c:
			return b
		else:
			return c
N = int(input())
l = []
for i in range(N):
	n = int(input())
	p = map(int, input().split())
	p = list(p)
	d = 0
	if len(p) == 2:
		d = 0
	else:
		p.sort()
		d = maxlen(len(p), p[-2], p[-1])
	l.append(d)
for i in range(N):
	print(l[i])


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	maximum = max(a)
	del a[a.index(maximum)]
	maximum2 = max(a)
	print(min(maximum2 - 1, len(a) - 1))


q = int(input())
b = []
for i in range(q):
	n = int(input())
	a = map(int, input().split())
	l = list(a)
	l.sort()
	l.reverse()
	b.append(min(l[1] - 1, len(l) - 2))
for i in range(q):
	print(b[i])


queries = int(input())
query_n = []
ladder_planks = []
for query in range(queries):
	n = int(input())
	query_n.append(n)
	planks = input().split(' ')
	ladder_planks.append(planks)

def to_integer(planks, n):
	for i in range(n):
		planks[i] = int(planks[i])

def verify_ladder(n, planks):
	k = n - 2
	to_integer(planks, n)
	planks.sort()
	if n == 2:
		print(0)
	else:
		print(min(planks[n - 2] - 1, n - 2))
for i in range(queries):
	verify_ladder(query_n[i], ladder_planks[i])


t = int(input())
for _ in range(t):
	n = int(input())
	nl = list(map(int, input().split()))
	nl = sorted(nl, reverse=True)
	base1 = nl[0]
	base2 = nl[1]
	k = 0
	for i in range(2, len(nl)):
		if k == base1 - 1 or k == base2 - 1:
			break
		k += 1
	print(k)


for j in range(int(input())):
	n = int(input())
	(*a,) = sorted(map(int, input().split()), reverse=True)
	print(min(len(a) - 2, a[1] - 1) if len(a) > 2 else 0)


def check(k, logs):
	cnt = 0
	for i in logs:
		if i > k:
			cnt += 1
		if cnt == 2:
			break
	return cnt == 2
t = int(input())
for i in range(t):
	left = 0
	right = int(input()) - 1
	logs = list(map(int, input().split()))
	while right - left > 1:
		mid = (left + right) // 2
		if check(mid, logs):
			left = mid
		else:
			right = mid
	print(left)


for t in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	res1 = l[-2] - 1
	print(min(res1, n - 2))


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	max1 = 0
	max2 = 0
	for i in range(n):
		if a[i] > max1:
			max2 = max1
			max1 = a[i]
		else:
			max2 = max(max2, a[i])
	print(max(min(max2 - 1, n - 2), 0))


T = int(input())
for i in range(T):
	n = int(input())
	nums = sorted(list(map(int, input().split())))
	print(min(nums[-2] - 1, n - 2))


test_num = int(input())
while test_num:
	test_num -= 1
	arr_num = int(input())
	arr = input()
	num = [int(n) for n in arr.split()]
	num = sorted(num)
	result = min(num[-2] - 1, arr_num - 2)
	print(result)


(t, ans) = (int(input()), [])
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	if n < 3:
		ans.append(0)
		continue
	max_1 = max(arr[0], arr[1])
	max_2 = min(arr[0], arr[1])
	for i in range(2, n):
		num = arr[i]
		if num >= max_1:
			max_2 = max_1
			max_1 = num
		elif num >= max_2:
			max_2 = num
	k = min(max_2 - 1, n - 2)
	ans.append(k)
print(*ans, sep='\n')


t = int(input())
for i in range(t):
	k = int(input())
	a = [int(item) for item in input().split()]
	a.sort()
	print(min(len(a) - 2, a[-2] - 1))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	maxk = min(a[-1], a[-2]) - 1
	k = n - 2
	while k > -1 and a[k] >= 1:
		k -= 1
	print(min(maxk, n - k - 3))


n = int(input())
ll = []
for i in range(n):
	m = input()
	ll.append([int(j) for j in input().split()])

def isSt(pks):
	pks.sort()
	(k1, k2) = pks[-2:]
	d = min(k1, k2)
	if d > 1:
		r = d - 1 if len(pks) - 2 > d - 1 else len(pks) - 2
		print(r)
	else:
		print(0)
for k in ll:
	isSt(k)


def bigest(List):
	big = biger = 0
	for i in range(len(List)):
		if List[i] > biger:
			big = biger
			biger = List[i]
		elif List[i] >= big:
			big = List[i]
	return big
aq = int(input())
ladder = aq * [0]
for i in range(aq):
	false = input()
	q = input()
	ladder[i] = q.split()
	for j in range(len(ladder[i])):
		ladder[i][j] = int(ladder[i][j])
for i in range(aq):
	answer = 0
	big = bigest(ladder[i])
	for i in range(len(ladder[i]) - 2):
		if answer + 1 >= big:
			break
		answer += 1
	print(answer)


T = int(input())
for _ in range(T):
	n = int(input())
	a = sorted(map(int, input().split()))
	if n < 3:
		print(0)
		continue
	baseLength = min(a[-2:])
	steps = len(list(filter(lambda x: x >= 1, a[:-2])))
	print(min(steps, baseLength - 1))


t = int(input())
while t > 0:
	t -= 1
	n = input()
	s = input()
	s = list(map(int, s.split()))
	s.sort()
	k = s[len(s) - 2]
	i = 0
	while True:
		if i == k - 1 or i == len(s) - 2:
			break
		i += 1
	print(i)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

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

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

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

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

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

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = I()
	rr = []
	for _ in range(t):
		n = I()
		a = LI()
		a.sort()
		rr.append(max(0, min(a[-2] - 1, n - 2)))
	return JA(rr, '\n')
print(main())


numtest = int(input())
result = []
for i in range(numtest):
	numplank = int(input())
	lengths = list(map(lambda num: int(num), input().split()))
	lengths.sort(reverse=True)
	result.append(str(min(lengths[1] - 1, numplank - 2)))
print('\n'.join(result))


for _ in range(int(input())):
	n = int(input())
	l = [int(e) for e in input().split()]
	l.sort()
	b = min(l[-1], l[-2])
	i = n - 3
	if i < 0:
		print(0)
	else:
		print(min(i + 1, b - 1))


import sys
import math
from collections import defaultdict
strInp = lambda : input().strip().split()
intInp = lambda : list(map(int, strInp()))
for t in range(int(input())):
	n = int(input())
	arr = intInp()
	arr.sort(reverse=True)
	print(min(n - 2, arr[1] - 1))


import sys
import queue
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	k = min(a[-1], a[-2]) - 1
	while n < k + 2:
		k = k - 1
	print(k)


t = int(input())
for _ in range(t):
	n = int(input())
	u = list(map(int, input().split()))
	m1 = 0
	m2 = 0
	for i in range(n):
		if u[i] > m1:
			(m1, m2) = (u[i], m1)
		elif u[i] > m2:
			m2 = u[i]
	print(max(min(m2 - 1, n - 2), 0))


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	A = [int(i) for i in input().split()]
	A.sort()
	print(0 if n == 2 else min(n - 2, A[-2] - 1))


T = int(input())
ans = []
for _ in range(T):
	N = int(input())
	arr = list(map(int, input().split()))
	max_1 = max(arr)
	arr.remove(max_1)
	max_2 = max(arr)
	arr.remove(max_2)
	if max_2 >= 2 and N >= 3:
		ans.append(min(max_2 - 1, N - 2))
	else:
		ans.append(0)
for el in ans:
	print(el)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	print(min(n - 2, l[-2] - 1))


n = int(input())
for i in range(n):
	m = int(input())
	v = list(map(int, input().split()))
	v.sort()
	count = 0
	last = min(v[-1], v[-2])
	for j in range(m - 2):
		if v[j] <= last and count < last - 1:
			count += 1
	print(count)


def pro(arr):
	arr.sort()
	l = arr[-1]
	r = arr[-2]
	mini = min(l, r)
	maxi = mini - 1
	print(min(maxi, len(arr) - 2))
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	pro(arr)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	m1 = l[-1]
	m2 = l[-2]
	lmax = min(m1, m2)
	if lmax > len(l) - 2:
		print(len(l) - 2)
	elif len(l) - 2 == lmax:
		print(len(l) - 3)
	else:
		print(lmax - 1)


n = int(input())
for i in range(n):
	size = int(input())
	data = []
	data[:] = map(int, input().split())
	data.sort()
	if size == 2:
		print('0')
	else:
		(a, b) = (data[-2], data[-1])
		count = 0
		for j in range(len(data) - 2):
			if count + 1 < a:
				count += 1
		print(count)


def gns():
	return list(map(int, input().split()))
t = int(input())
for i in range(t):
	n = int(input())
	ns = gns()
	ns.sort()
	if n < 3:
		print(0)
		continue
	k = ns[-2] - 1
	if k <= 0:
		print(0)
		continue
	print(min(n - 2, k))


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a = sorted(a)
	rails = a[-2]
	rungs = len(a) - 2
	if rails > rungs:
		print(rungs)
	else:
		print(rails - 1)


n = int(input())
l = []
for i in range(n):
	p = int(input())
	k = list(map(int, input().split()))
	l.append(k)
res = []
for i in range(len(l)):
	f = max(l[i])
	l[i].remove(f)
	s = max(l[i])
	m = min(f, s)
	le = len(l[i]) - 1
	k = m - 1
	if le < k:
		res.append(le)
	else:
		res.append(k)
print('\n'.join(map(str, res)))


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	if n == 2:
		print(0)
	else:
		k = a[1] - 1
		if n - 2 >= k:
			print(k)
		else:
			print(n - 2)


def fastio():
	import sys
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
(t,) = I()
while t:
	t -= 1
	(n,) = I()
	a = I()
	a.sort()
	if n == 2:
		print(0)
	else:
		print(min(n - 2, a[-2] - 1))


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	ma = min(arr[-1], arr[-2])
	l = len(arr) - 2
	ans = 0
	if l >= ma:
		ans = ma - 1
	else:
		ans = l
	print(ans)


def get_max_steps(l):
	l.sort()
	k = 0
	(a, b) = (l[-1], l[-2])
	l.remove(a)
	l.remove(b)
	for i in l:
		if k + 1 < min(a, b):
			k += 1
	return k
n = int(input())
for _ in range(n):
	t = input()
	lengths = list(map(int, input().split()))
	print(get_max_steps(lengths))


import math
import os
import random
import re
import sys

def ladder(arr, ni):
	p1 = arr[-1]
	p2 = arr[-2]
	count = min(p2 - 1, ni - 2)
	print(count)
n = int(input())
while n:
	ni = int(input())
	arr = sorted(list(map(int, input().split())))
	ladder(arr, ni)
	n -= 1


import bisect

def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		planks = list(map(int, input().split()))
		planks.sort()
		for k in range(planks[-1], -1, -1):
			index = bisect.bisect(planks, k)
			if n - index >= 2 and n - 2 >= k:
				print(k)
				break
main()


T = int(input())
for _ in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	if len(a) <= 1:
		print(0)
	else:
		k = a[1] - 1
		print(min(n - 2, k))


n = int(input())
for i in range(n):
	m = int(input())
	v = list(map(int, input().rstrip().split()))
	v = sorted(v)
	if min(v[m - 2], m - 2) > 0:
		print(min(v[m - 2] - 1, m - 2))
	else:
		print('0')


for i in range(int(input())):
	N = int(input())
	X = sorted(list(map(int, input().split())))
	if N == 2:
		print(0)
	else:
		K = X[-2] - 1
		if K <= N - 2:
			print(K)
		else:
			print(N - 2)


t = int(input())
for i in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort()
	print(min(min(a[-1], a[-2]) - 1, n - 2))


def sol():
	n = int(input())
	A = [int(i) for i in input().split()]
	A.sort(reverse=True)
	print(min(A[1] - 1, n - 2))

def s():
	n = int(input())
	for _ in range(n):
		sol()
s()


T = int(input())
for t in range(T):
	n = int(input())
	A = [int(i) for i in input().split()]
	A.sort()
	ans = min(A[-1], A[-2])
	print(max(0, min(n - 2, max(0, ans - 1))))


n = int(input())
for i in range(n):
	m = int(input())
	l = list(map(int, input().split()))
	r = max(l)
	l.remove(r)
	p = max(l)
	l.remove(p)
	s = 0
	for i in range(m - 2):
		if s < p - 1:
			s += 1
	print(s)


n = int(input())
for i in range(n):
	p = int(input())
	a = [int(i) for i in input().split()]
	max_ = max(a[0], a[1])
	secondmax = min(a[0], a[1])
	for i in range(2, len(a)):
		if a[i] > max_:
			secondmax = max_
			max_ = a[i]
		elif a[i] > secondmax:
			secondmax = a[i]
	ans = min(secondmax - 1, p - 2)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = []
	l = list(map(int, input().split()))
	for t in l:
		if t >= 1:
			a.append(t)
	m = max(a)
	a.remove(m)
	m1 = max(a)
	a.remove(m1)
	v = len(a)
	while v >= m or v >= m1:
		v -= 1
	print(v)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	max1 = max(a[0], a[1])
	max2 = min(a[0], a[1])
	for i in range(2, n):
		if a[i] >= max1:
			max2 = max1
			max1 = a[i]
		elif a[i] >= max2:
			max2 = a[i]
	print(min(max2 - 1, n - 2))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	a = max(l)
	l.remove(a)
	b = max(l)
	l.remove(b)
	c = min(a, b) - 1
	d = len(l)
	print(min(c, d))


blah = int(input())
for _ in range(blah):
	n = int(input())
	lengths = list(map(int, input().split()))
	lrgst_idx = 0 if lengths[0] > lengths[1] else 1
	snd_lrgst_idx = 1 - lrgst_idx
	for i in range(2, n):
		if lengths[i] > lengths[snd_lrgst_idx]:
			snd_lrgst_idx = i
		if lengths[snd_lrgst_idx] > lengths[lrgst_idx]:
			g = snd_lrgst_idx
			snd_lrgst_idx = lrgst_idx
			lrgst_idx = g
	max_k = min(lengths[lrgst_idx], lengths[snd_lrgst_idx])
	print(min(max_k - 1, n - 2))


t = int(input())
for i in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	a.sort()
	a1 = a[n - 1]
	a2 = a[n - 2]
	if a1 >= n - 1 and a2 >= n - 1:
		print(n - 2)
	else:
		print(a2 - 1)


for _ in range(int(input())):
	N = int(input())
	L = list(map(int, input().split()))
	L.sort(reverse=True)
	K = min(L[0], L[1]) - 1
	if K > N - 2:
		print(N - 2)
	else:
		print(K)


for _ in range(int(input())):
	n = int(input())
	l = sorted([int(q) for q in input().split()])
	m = l[-2]
	answ = m - 1
	if len(l) - 2 <= answ:
		print(len(l) - 2)
	else:
		print(answ)


for i in range(int(input())):
	k = int(input())
	data = list(map(int, input().split()))
	if k == 2:
		print(0)
	else:
		max_1 = -1
		max_2 = -1
		for i in range(k):
			if data[i] >= max_1:
				max_2 = max_1
				max_1 = data[i]
			elif data[i] > max_2:
				max_2 = data[i]
		print(min(max_2 - 1, k - 2))


import operator
q = 0
n = 0
q = input()
q = int(q)
list = []
for _ in range(q):
	list.clear
	n = input()
	n = int(n)
	list = input()
	list = list.split()
	for index in range(len(list)):
		list[index] = int(list[index])
	if len(list) < 3:
		print(0)
	else:
		(index, maxi) = max(enumerate(list), key=operator.itemgetter(1))
		del list[index]
		(index, maxi2) = max(enumerate(list), key=operator.itemgetter(1))
		if maxi2 - 1 <= len(list) - 1:
			print(maxi2 - 1)
		else:
			print(len(list) - 1)


t = int(input())
for _ in range(t):
	n = int(input())
	lengths = list(map(int, input().split()))
	lengths = sorted(lengths)
	a = lengths[len(lengths) - 2]
	answer = min(n - 2, a - 1)
	print(answer)


def main():
	n = int(input())
	for i in range(n):
		c = int(input())
		vals = [int(v) for v in input().split()]
		vals.sort(reverse=True)
		rows = vals[0:2]
		sz = min(rows) - 1
		res = min(sz, len(vals) - 2)
		print(res if res > 0 else 0)
main()


request_count = int(input())
for request in range(request_count):
	woods_count = int(input())
	woods = input().split()
	if woods_count > 2:
		for value in range(len(woods)):
			woods[value] = int(woods[value])
		main_w = [0, 0]
		main_w[0] = max(woods)
		woods.remove(main_w[0])
		main_w[1] = max(woods)
		woods.remove(main_w[1])
		max_steps = min(main_w) - 1
		if max_steps > len(woods):
			print(len(woods))
		else:
			print(max_steps)
	else:
		print(0)


for _ in range(int(input())):
	lens = int(input())
	size = sorted([int(x) for x in input().split()], reverse=True)
	base = size[:2]
	ladders = [x for x in size[2:] if x > 0]
	if len(ladders) < min(base):
		print(len(ladders))
	elif len(ladders) >= min(base):
		print(min(base) - 1)
	else:
		print(0)


T = int(input())
for i in range(T):
	n = int(input())
	A = list(map(int, input().split()))
	max1 = 0
	max2 = 0
	for elem in A:
		if elem > max1:
			max2 = max1
			max1 = elem
		elif elem > max2:
			max2 = elem
	k1 = max2 - 1
	k2 = len(A) - 2
	if k2 < 0:
		k2 = 0
	if k1 < 0:
		k1 = 0
	print(min(k1, k2))


t = int(input())
while t > 0:
	n = int(input())
	a = [int(i) for i in input().split()]
	a.sort()
	k = min(a[-1], a[-2]) - 1
	if len(a) - 2 >= k:
		print(k)
	else:
		print(len(a) - 2)
	t -= 1


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	m = max(l)
	l.remove(m)
	n = max(l)
	l.remove(n)
	km = min(n, m)
	x = min(km - 1, len(l))
	print(x)


t = int(input())
for x in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	if A[0] > A[1]:
		m_idx = 0
		last_m_idx = 1
	else:
		m_idx = 1
		last_m_idx = 0
	for i in range(2, n):
		if A[i] > A[m_idx]:
			last_m_idx = m_idx
			m_idx = i
		elif A[i] > A[last_m_idx]:
			last_m_idx = i
	print(min(min(A[m_idx], A[last_m_idx]) - 1, n - 2))


import math
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	a = l[-2]
	print(min(a - 1, n - 2))


import sys
inf = float('inf')
(mod, MOD) = (1000000007, 998244353)

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

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

def input():
	return sys.stdin.readline().strip()
T = int(input())
while T > 0:
	n = int(input())
	Arr = get_array()
	Arr.sort()
	mini = min(Arr[-1], Arr[-2]) - 1
	print(min(mini, n - 2))
	T -= 1


T = int(input())
for i in range(0, T):
	n = int(input())
	p = [int(x) for x in input().split()]
	if n == 2:
		print(0)
	else:
		p = sorted(p)
		print(min(n - 2, p[n - 2] - 1))


t = int(input())
for i in range(t):
	n = int(input())
	inp = list(map(int, input().split()))
	inp.sort()
	a = inp[len(inp) - 1]
	b = inp[len(inp) - 2]
	x = b - 1
	flag = 0
	k = len(inp) - 2
	while k > x:
		k -= 1
		if k == 0:
			print(0)
			flag = 1
			break
	if flag == 0:
		print(k)


t = int(input())
for iter in range(t):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	m = min(a[n - 1], a[n - 2]) - 1
	print(min(n - 2, m))


t = int(input())
for i in range(t):
	n = int(input())
	arr = input().split()
	if n == 2 or n == 1:
		print(0)
	else:
		arr = list(map(int, arr))
		arr.sort(reverse=True)
		(a, b) = (arr[0], arr[1])
		if n - 2 >= int(b):
			print(int(b) - 1)
		else:
			print(n - 2)


t = int(input())
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	count = 0
	a.pop(0)
	x = a.pop(0)
	for i in a:
		if x > count + 1:
			count += 1
	print(count)


for _ in range(int(input())):
	n = int(input())
	a = sorted(list(filter(lambda x: x >= 1, map(int, input().split()))))
	print(min(len(a) - 2, a[-2] - 1))


m = int(input())
for _ in range(m):
	n = int(input())
	l = list(map(int, input().split()))
	l = sorted(l)
	l.reverse()
	k = min(l[0], l[1])
	ans = min(k - 1, n - 2)
	if n < 3 or ans <= 0:
		print(0)
	else:
		print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	x = l[-2] - 1
	l.pop()
	l.pop()
	if len(l) >= x:
		print(x)
	else:
		print(len(l))


n = int(input())
l = []
for i in range(n):
	z = int(input())
	l.append([int(x) for x in input().split()])
for elem in l:
	elem.sort(reverse=True)
	m1 = elem[1] - 1
	m2 = len(elem) - 2
	print(min(m1, m2))