Consider a sequence of integers $a_1, a_2, \ldots, a_n$. In one move, you can select any element of the sequence and delete it. After an element is deleted, all elements to the right are shifted to the left by $1$ position, so there are no empty spaces in the sequence. So after you make a move, the sequence's length decreases by $1$. The indices of the elements after the move are recalculated.

E. g. let the sequence be $a=[3, 2, 2, 1, 5]$. Let's select the element $a_3=2$ in a move. Then after the move the sequence will be equal to $a=[3, 2, 1, 5]$, so the $3$-rd element of the new sequence will be $a_3=1$ and the $4$-th element will be $a_4=5$.

You are given a sequence $a_1, a_2, \ldots, a_n$ and a number $k$. You need to find the minimum number of moves you have to make so that in the resulting sequence there will be at least $k$ elements that are equal to their indices, i. e. the resulting sequence $b_1, b_2, \ldots, b_m$ will contain at least $k$ indices $i$ such that $b_i = i$.


-----Input-----

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

Each test case consists of two consecutive lines. The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 2000$). The second line contains a sequence of integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$). The numbers in the sequence are not necessarily different.

It is guaranteed that the sum of $n$ over all test cases doesn't exceed $2000$.


-----Output-----

For each test case output in a single line:

$-1$ if there's no desired move sequence;

otherwise, the integer $x$ ($0 \le x \le n$) — the minimum number of the moves to be made so that the resulting sequence will contain at least $k$ elements that are equal to their indices.


-----Examples-----

Input
4
7 6
1 1 2 3 4 5 6
5 2
5 1 3 2 3
5 2
5 5 5 5 4
8 4
1 2 3 3 2 2 5 5
Output
1
2
-1
2


-----Note-----

In the first test case the sequence doesn't satisfy the desired condition, but it can be provided by deleting the first element, hence the sequence will be $[1, 2, 3, 4, 5, 6]$ and $6$ elements will be equal to their indices.

In the second test case there are two ways to get the desired result in $2$ moves: the first one is to delete the $1$-st and the $3$-rd elements so that the sequence will be $[1, 2, 3]$ and have $3$ elements equal to their indices; the second way is to delete the $2$-nd and the $3$-rd elements to get the sequence $[5, 2, 3]$ with $2$ desired elements.

Source: codeforces | Difficulty: HARD
Tags: Dynamic programming

Sorting

Complete search


Solutions:
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 * 10 ** 9, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=-1, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
for ik in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	dp = [[-2001 for i in range(n + 1)] for j in range(n + 1)]
	dp[0][0] = 0
	ans = n + 1
	for i in range(1, n + 1):
		for j in range(i + 1):
			t = 0
			if i - j == l[i - 1]:
				t = 1
			if j == 0:
				dp[i][j] = dp[i - 1][j] + t
			else:
				dp[i][j] = max(dp[i - 1][j] + t, dp[i - 1][j - 1])
			if dp[i][j] >= k:
				ans = min(ans, j)
	if ans > n:
		print(-1)
	else:
		print(ans)


import sys
input = sys.stdin.readline

def solve():
	(n, k) = map(int, input().split())
	A = list(map(int, input().split()))
	A = [x - 1 for x in A]
	dp = [[-1 << 32] * (n + 1) for _ in range(n + 1)]
	dp[0][0] = 0
	dp[0][1] = int(A[0] == 0)
	for i in range(1, n):
		for j in range(i + 2):
			if j == 0:
				dp[i][j] = 0
				continue
			drop = dp[i - 1][j]
			keep = dp[i - 1][j - 1] + int(A[i] == j - 1)
			dp[i][j] = max(drop, keep)
	for j in range(n, -1, -1):
		if dp[n - 1][j] >= k:
			print(n - j)
			return
	print(-1)
	return
for nt in range(int(input())):
	solve()


NUM = int(input())
for T in range(0, NUM):
	(N, K) = map(int, input().split())
	numlist = list(map(int, input().split()))
	for i in range(0, N):
		numlist[i] -= i + 1
	dp = []
	ans = 10 ** 10
	for i in range(0, N):
		mx = 1
		for j in range(0, i):
			if numlist[j] >= numlist[i] and numlist[j] - numlist[i] < i - j:
				mx = max(mx, dp[j] + 1)
		if numlist[i] > 0:
			mx = -N
		dp.append(mx)
		if mx == K:
			ans = min(ans, -numlist[i])
	if ans == 10 ** 10:
		print(-1)
	else:
		print(ans)


from collections import deque
import heapq
from math import sqrt
import operator
from operator import itemgetter
import sys
import copy
inf_var = 0
if inf_var == 1:
	inf = open('input.txt', 'r')
else:
	inf = sys.stdin
input = inf.readline

def read_one_int():
	return int(input().rstrip('\n'))

def read_one_float():
	return float(input().rstrip('\n'))

def read_list_of_ints():
	res = [int(val) for val in input().rstrip('\n').split(' ')]
	return res

def read_str():
	return input().rstrip()

def main():
	tests = read_one_int()
	for _ in range(tests):
		(n, k) = read_list_of_ints()
		elements = read_list_of_ints()
		graph = [[] for _ in range(n)]
		for i in range(n - 1, -1, -1):
			need_to_del_i = i + 1 - elements[i]
			if need_to_del_i < 0:
				continue
			for j in range(i - 1, -1, -1):
				need_to_del_j = j + 1 - elements[j]
				if need_to_del_j < 0 or need_to_del_j > need_to_del_i:
					continue
				if j < need_to_del_j or need_to_del_i - need_to_del_j > i - j - 1:
					continue
				graph[i].append(j)
		cache = {}

		def count_max(v):
			if v in cache:
				return cache[v]
			if v + 1 - elements[v] >= 0:
				res = 0
				for u in graph[v]:
					res = max(res, count_max(u))
				cache[v] = res + 1
				return res + 1
			else:
				cache[v] = 0
				return 0
		res = -1
		for i in range(n):
			cur_res = count_max(i)
			if cur_res >= k:
				if res == -1:
					res = i + 1 - elements[i]
				else:
					res = min(res, i + 1 - elements[i])
		print(res)
main()


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

def judge(remove, arr, k):
	n = len(arr)
	dp = [[0 for j in range(remove + 1)] for i in range(n + 1)]
	for i in range(n - 1, -1, -1):
		limit = min(i, remove)
		for j in range(limit + 1):
			if arr[i] == j:
				base = 1
			else:
				base = 0
			num1 = base + dp[i + 1][j]
			num2 = -2147483647
			if j + 1 <= remove:
				num2 = dp[i + 1][j + 1]
			dp[i][j] = max(num1, num2)
	if dp[0][0] >= k:
		return True
	else:
		return False

def main(t):
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	for i in range(n):
		arr[i] = i + 1 - arr[i]
	ans = 0
	front = 0
	rear = n - k + 1
	while front < rear:
		mid = (front + rear) // 2
		if judge(mid, arr, k):
			rear = mid
		else:
			front = mid + 1
	if front == n - k + 1:
		print(-1)
	else:
		print(front)
T = int(input())
t = 1
while t <= T:
	main(t)
	t += 1


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	DP = [[0 for i in range(n + 1)] for j in range(n + 1)]
	for m in range(1, n + 1):
		for d in range(0, m + 1):
			if m - a[m - 1] == d:
				if d == 0:
					DP[m][0] = DP[m - 1][0] + 1
				else:
					DP[m][d] = max(DP[m - 1][d] + 1, DP[m - 1][d - 1])
			elif d == 0:
				DP[m][0] = DP[m - 1][0]
			else:
				DP[m][d] = max(DP[m - 1][d], DP[m - 1][d - 1])
	operations = None
	for d in range(n + 1):
		if DP[n][d] >= k:
			operations = d
			break
	if operations != None:
		print(operations)
	else:
		print(-1)


from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys

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

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

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

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

def getListGraph():
	return list(map(lambda x: int(x) - 1, input().split()))

def getArray(intn):
	return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
inf = float('inf')
eps = 10 ** (-10)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
T = getN()
for _ in range(T):
	(N, K) = getNM()
	A = [0] + getList()
	prev = [0] * (N + 1)
	for i in range(1, N + 1):
		next = [0] * (N + 1)
		for j in range(i):
			next[j + 1] = max(next[j + 1], prev[j])
			next[j] = max(next[j], prev[j] + (i - j == A[i]))
		prev = next
	for i in range(N + 1):
		if prev[i] >= K:
			print(i)
			break
	else:
		print(-1)


import sys
from sys import stdin
tt = int(stdin.readline())
for loop in range(tt):
	(n, k) = map(int, stdin.readline().split())
	a = list(map(int, stdin.readline().split()))
	dp = [[float('-inf')] * (n + 1) for i in range(n + 1)]
	dp[0][0] = 0
	for i in range(n + 1):
		for j in range(n + 1):
			if j != 0:
				dp[i][j] = max(dp[i][j], dp[i][j - 1])
			if i != 0 and j != 0:
				if a[j - 1] == i:
					dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1)
				else:
					dp[i][j] = max(dp[i][j], dp[i - 1][j - 1])
	ans = float('inf')
	for i in range(n + 1):
		for j in range(n + 1):
			if dp[i][j] >= k:
				ans = min(ans, j - i)
	print(ans if ans != float('inf') else -1)


import sys
input = sys.stdin.readline

def solve():
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	d = [-1000000] * n
	ans = 1000000
	for i in range(0, n):
		z = -1000000
		v = a[i]
		w = a[i] - i
		if i >= v - 1:
			z = 0
		for j in range(i):
			if a[j] < v and a[j] - j >= w:
				z = max(z, d[j])
		d[i] = z + 1
		if z + 1 >= k:
			ans = min(ans, 1 - w)
	if ans >= 1000000:
		print(-1)
	else:
		print(ans)
for i in range(int(input())):
	solve()


def naiveSolve():
	return

def main():
	t = int(input())
	allans = []
	for _ in range(t):
		(n, k) = readIntArr()
		a = readIntArr()
		dp = [[-inf for __ in range(n + 1)] for ___ in range(n)]
		for i in range(n):
			for j in range(i + 2):
				if a[i] == i - j + 1:
					add = 1
				else:
					add = 0
				if i - 1 >= 0:
					dp[i][j] = max(dp[i][j], dp[i - 1][j] + add)
				else:
					dp[i][j] = max(dp[i][j], add)
				if j >= 1:
					if i == 0:
						assert j == 1
						dp[i][j] = 0
					else:
						dp[i][j] = max(dp[i][j], dp[i - 1][j - 1])
		ans = -1
		for delCnts in range(n + 1):
			if dp[n - 1][delCnts] >= k:
				ans = delCnts
				break
		allans.append(ans)
	multiLineArrayPrint(allans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

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

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(l, r):
	print('? {} {}'.format(l, r))
	sys.stdout.flush()
	return int(input())

def answerInteractive(x):
	print('! {}'.format(x))
	sys.stdout.flush()
inf = float('inf')
MOD = 998244353
from math import gcd, floor, ceil
for _abc in range(1):
	main()


import sys, os
from io import BytesIO, IOBase
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(stdin, stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = pow(10, 9) + 7
mod2 = 998244353

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

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

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

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

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(int(inp())):
	(n, k) = mp()
	arr = lmp()
	dp = l2d(n, n)
	ans = inf
	for i in range(n):
		for j in range(i + 1):
			if arr[i] == j + 1:
				dp[i][j] = 1 + dp[i - 1][j - 1]
			else:
				dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1])
			if dp[i][j] == k:
				ans = min(ans, i - j)
	print(ans if ans != inf else -1)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = [0] + list(map(int, input().split()))
	dp = [0 for i in range(n + 1)]
	inf = float('inf')
	an = inf
	for i in range(1, n + 1):
		b = -1
		for j in range(0, i):
			if a[i] > a[j] and a[i] - a[j] <= i - j:
				b = max(b, dp[j] + 1)
		dp[i] = b
		if b >= k:
			an = min(an, i - a[i])
	if an == inf:
		print(-1)
	else:
		print(an)


def printResult():
	for i in range(n, 0, -1):
		if f[n][i] >= k:
			print(n - i)
			return
	print(-1)
test = int(input())
for _ in range(test):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	a = [0] + a
	f = [[0 for _ in range(n + 1)] for _ in range(n + 1)]
	for i in range(1, n + 1):
		for j in range(1, i + 1):
			f[i][j] = f[i - 1][j]
			if a[i] == j:
				f[i][j] = max(f[i][j], f[i - 1][j - 1] + 1)
			else:
				f[i][j] = max(f[i][j], f[i - 1][j - 1])
	printResult()


import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	(n, k) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	dp = [[0] * (n + 1) for i in range(n)]
	if a[0] == 1:
		dp[0][0] = 1
	for i in range(1, n):
		if a[i] == i + 1:
			dp[i][0] = dp[i - 1][0] + 1
		else:
			dp[i][0] = dp[i - 1][0]
	for i in range(1, n):
		for j in range(i + 1):
			if j != 0:
				dp[i][j] = dp[i - 1][j - 1]
			if a[i] == i + 1 - j:
				dp[i][j] = max(dp[i][j], dp[i - 1][j] + 1)
			else:
				dp[i][j] = max(dp[i][j], dp[i - 1][j])
	ans = 1000000000.0
	for i in range(n):
		for j in range(n):
			if dp[i][j] >= k:
				ans = min(ans, j)
	if ans > 100000000.0:
		ans = -1
	print(ans)


import sys
from os import path
if path.exists('Input.txt'):
	sys.stdin = open('Input.txt', 'r')
	sys.stdout = open('Output.txt', 'w')
input = lambda : sys.stdin.readline().rstrip()

def solve_tc():
	(n, k) = map(int, input().split())
	s = list(map(int, input().split()))
	s1 = [i + 1 - s[i] for i in range(n)]
	dp = [-1] * (n + 2)
	dp[0] = 0
	for i in range(n):
		for j in range(i, -1, -1):
			if dp[j] != -1:
				dp[j + 1] = max(dp[j], dp[j + 1])
				if s1[i] == j:
					dp[j] += 1
	for i in range(n + 2):
		if dp[i] >= k:
			return str(i)
	else:
		return '-1'
t = int(input())
for _ in range(t):
	sys.stdout.write(solve_tc() + '\n')


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

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

def inp():
	return int(input())
import math
import copy
from collections import defaultdict, deque
import heapq
import sys
sys.setrecursionlimit(10 ** 5)
mod = 10 ** 9 + 7
input = sys.stdin.buffer.readline
t = inp()
for _ in range(t):
	(n, k) = var()
	arr = a()
	dp = [[0] * (n + 1) for _ in range(n + 1)]
	dp[0][0] = 0
	for i in range(1, n + 1):
		for j in range(i + 1):
			if j == 0:
				dp[i][j] = dp[i - 1][j] + int(arr[i - 1] == i)
				continue
			dp[i][j] = max(dp[i - 1][j - 1], dp[i - 1][j] + int(arr[i - 1] == i - j))
	found = False
	for j in range(n + 1):
		if dp[n][j] >= k:
			found = True
			break
	if found:
		print(j)
	else:
		print(-1)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	A = list(map(int, input().split()))
	dp = [[0] * (n + 1) for _ in range(n + 1)]
	ans = float('inf')
	for i in range(1, n + 1):
		for j in range(i + 1):
			if j == 0:
				dp[i][j] = dp[i - 1][j] + (A[i - 1] == i)
			else:
				dp[i][j] = max(dp[i - 1][j] + (A[i - 1] == i - j), dp[i - 1][j - 1])
			if dp[i][j] >= k:
				ans = min(ans, j)
	print(ans if ans < float('inf') else -1)


import sys
import io, os
import math
from heapq import *
gcd = math.gcd
sqrt = math.sqrt
ceil = math.ceil
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def strinp(testcases):
	k = 5
	if testcases == -1 or testcases == 1:
		k = 1
	f = str(input())
	f = f[2:len(f) - k]
	return f

def ind(ch):
	return ord(ch) - ord('a')

def main():
	t = int(input())
	for _ in range(t):
		arr = list(map(int, input().split()))
		n = arr[0]
		k = arr[1]
		a = list(map(int, input().split()))
		dp = [[0 for i in range(n + 1)] for j in range(n + 1)]
		ans = 10 ** 9
		for i in range(1, n + 1):
			for j in range(i):
				dp[i][j] = max(dp[i - 1][j] + int(a[i - 1] == i - j), dp[i][j])
				dp[i][j + 1] = dp[i - 1][j]
				if dp[i][j] >= k:
					ans = min(ans, j)
		if ans == 10 ** 9:
			print(-1)
		else:
			print(ans)
main()


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


t = int(input())
while t:
	t -= 1
	(n, k) = [int(c) for c in input().split()]
	arr = [0] + [int(c) for c in input().split()]
	dp = [[0 for x in range(n + 1)] for xi in range(n + 1)]
	for i in range(1, n + 1):
		for j in range(i + 1):
			dp[i][j] = max(dp[i][j], dp[i - 1][j - 1])
			if arr[i] == i - j:
				if i - 1 >= j:
					dp[i][j] = max(dp[i][j], dp[i - 1][j] + 1)
			elif i - 1 >= j:
				dp[i][j] = max(dp[i - 1][j], dp[i][j])
	for i in range(n + 1):
		if dp[-1][i] >= k:
			print(i)
			break
	else:
		print(-1)


import sys, os
from math import *
from bisect import *
from heapq import *
from collections import *
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		(n, k) = MI()
		arr = list(MI())
		found = False
		out = n
		dp = [[0 for i in range(n + 1)] for j in range(n + 1)]
		for i in range(n):
			dp[i + 1][0] = dp[i][0]
			if arr[i] == i + 1:
				dp[i + 1][0] += 1
			if dp[i + 1][0] >= k:
				out = 0
				print(0)
				break
		if out == 0:
			continue
		for i in range(1, n + 1):
			for j in range(1, i):
				dp[i][j] = max(dp[i - 1][j - 1], dp[i - 1][j])
				if arr[i - 1] == i - j:
					dp[i][j] = max(dp[i][j], dp[i - 1][j] + 1)
				if dp[i][j] >= k:
					found = True
					out = min(out, j)
		if not found:
			print(-1)
		else:
			print(out)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

def outP(var):
	sys.stdout.write(str(var) + '\n')
MOD = 10 ** 9 + 7
mod = 998244353
main()


t = int(input())
for pro in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split(' ')))
	dp = [[0 for i in range(n + 1)] for kk in range(n)]
	dp[0][0] = 1 if a[0] == 1 else 0
	for i in range(1, n):
		for j in range(i + 2):
			if a[i] == i + 1 - j:
				dp[i][j] = max(1 + dp[i - 1][j], dp[i - 1][j - 1])
			else:
				dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1])
	ans = -1
	for truck in range(n + 1):
		if dp[-1][truck] >= k:
			ans = truck
			break
	print(ans)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	nums = list(map(int, input().split()))
	dp = [[0 for j in range(n + 1)] for i in range(n + 1)]
	ans = n + 1
	for i in range(n):
		for j in range(i + 2):
			dp[i + 1][j] = dp[i][j - 1]
			if nums[i] == i - j + 1:
				dp[i + 1][j] = max(dp[i + 1][j], dp[i][j] + 1)
			else:
				dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
			if dp[i + 1][j] >= k:
				ans = min(ans, j)
				break
	if ans == n + 1:
		print(-1)
	else:
		print(ans)


import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(10001)]
prime[0] = prime[1] = False

def SieveOfEratosthenes(n=10000):
	p = 2
	c = 0
	while p <= n:
		if prime[p] == True:
			c += 1
			for i in range(p, n + 1, p):
				prime[i] = False
		p += 1

class DSU:

	def __init__(self, R, C):
		self.par = range(R * C + 1)
		self.rnk = [0] * (R * C + 1)
		self.sz = [1] * (R * C + 1)

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

	def union(self, x, y):
		(xr, yr) = (self.find(x), self.find(y))
		if xr == yr:
			return
		if self.rnk[xr] < self.rnk[yr]:
			(xr, yr) = (yr, xr)
		if self.rnk[xr] == self.rnk[yr]:
			self.rnk[xr] += 1
		self.par[yr] = xr
		self.sz[xr] += self.sz[yr]

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

	def top(self):
		return self.size(len(self.sz) - 1) - 1

class LazySegTree:

	def __init__(self, _op, _e, _mapping, _composition, _id, v):

		def set(p, x):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			_d[p] = x
			for i in range(1, _log + 1):
				_update(p >> i)

		def get(p):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			return _d[p]

		def prod(l, r):
			assert 0 <= l <= r <= _n
			if l == r:
				return _e
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r >> i)
			sml = _e
			smr = _e
			while l < r:
				if l & 1:
					sml = _op(sml, _d[l])
					l += 1
				if r & 1:
					r -= 1
					smr = _op(_d[r], smr)
				l >>= 1
				r >>= 1
			return _op(sml, smr)

		def apply(l, r, f):
			assert 0 <= l <= r <= _n
			if l == r:
				return
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r - 1 >> i)
			l2 = l
			r2 = r
			while l < r:
				if l & 1:
					_all_apply(l, f)
					l += 1
				if r & 1:
					r -= 1
					_all_apply(r, f)
				l >>= 1
				r >>= 1
			l = l2
			r = r2
			for i in range(1, _log + 1):
				if l >> i << i != l:
					_update(l >> i)
				if r >> i << i != r:
					_update(r - 1 >> i)

		def _update(k):
			_d[k] = _op(_d[2 * k], _d[2 * k + 1])

		def _all_apply(k, f):
			_d[k] = _mapping(f, _d[k])
			if k < _size:
				_lz[k] = _composition(f, _lz[k])

		def _push(k):
			_all_apply(2 * k, _lz[k])
			_all_apply(2 * k + 1, _lz[k])
			_lz[k] = _id
		_n = len(v)
		_log = _n.bit_length()
		_size = 1 << _log
		_d = [_e] * (2 * _size)
		_lz = [_id] * _size
		for i in range(_n):
			_d[_size + i] = v[i]
		for i in range(_size - 1, 0, -1):
			_update(i)
		self.set = set
		self.get = get
		self.prod = prod
		self.apply = apply
MIL = 1 << 20

def makeNode(total, count):
	return total * MIL + count

def getTotal(node):
	return math.floor(node / MIL)

def getCount(node):
	return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)

def nodeOp(node1, node2):
	return node1 + node2
	return makeNode(getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2))
identityMapping = -1

def mapping(tag, node):
	if tag == identityMapping:
		return node
	count = getCount(node)
	return makeNode(tag * count, count)

def composition(mapping1, mapping2):
	return mapping1 if mapping1 != identityMapping else mapping2

def memodict(f):

	class memodict(dict):

		def __missing__(self, key):
			ret = self[key] = f(key)
			return ret
	return memodict().__getitem__

def pollard_rho(n):
	if n & 1 == 0:
		return 2
	if n % 3 == 0:
		return 3
	s = (n - 1 & 1 - n).bit_length() - 1
	d = n >> s
	for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
		p = pow(a, d, n)
		if p == 1 or p == n - 1 or a % n == 0:
			continue
		for _ in range(s):
			prev = p
			p = p * p % n
			if p == 1:
				return math.gcd(prev - 1, n)
			if p == n - 1:
				break
		else:
			for i in range(2, n):
				(x, y) = (i, (i * i + 1) % n)
				f = math.gcd(abs(x - y), n)
				while f == 1:
					(x, y) = ((x * x + 1) % n, (y * y + 1) % n)
					y = (y * y + 1) % n
					f = math.gcd(abs(x - y), n)
				if f != n:
					return f
	return n

@memodict
def prime_factors(n):
	if n <= 1:
		return Counter()
	f = pollard_rho(n)
	return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)

def distinct_factors(n):
	factors = [1]
	for (p, exp) in prime_factors(n).items():
		factors += [p ** i * factor for factor in factors for i in range(1, exp + 1)]
	return factors

def all_factors(n):
	(small, large) = ([], [])
	for i in range(1, int(n ** 0.5) + 1, 2 if n & 1 else 1):
		if not n % i:
			small.append(i)
			large.append(n // i)
	if small[-1] == large[-1]:
		large.pop()
	large.reverse()
	small.extend(large)
	return small

def binarySearch(arr, n, i, key):
	left = 0
	right = n - 1
	mid = 0
	res = n
	while left <= right:
		mid = (right + left) // 2
		if arr[mid][i] > key:
			res = mid
			right = mid - 1
		else:
			left = mid + 1
	return res

def binarySearch1(arr, n, i, key):
	left = 0
	right = n - 1
	mid = 0
	res = -1
	while left <= right:
		mid = (right + left) // 2
		if arr[mid][i] > key:
			right = mid - 1
		else:
			res = mid
			left = mid + 1
	return res
t = 1
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	dp = [[0 for j in range(n + 1)] for i in range(n)]
	dp[0][0] = int(a[0] == 1)
	for i in range(1, n):
		dp[i][0] = dp[i - 1][0] + int(a[i] == i + 1)
	for i in range(n):
		for j in range(1, i + 1):
			dp[i][j] = max(dp[i - 1][j - 1], dp[i - 1][j] + int(a[i] == i + 1 - j))
	ch = -1
	for i in range(n):
		if dp[-1][i] >= k:
			ch = i
			break
	print(ch)


import sys
input = sys.stdin.readline

def main():
	(n, k) = map(int, input().split())
	alst = list(map(int, input().split()))
	inf = -10 ** 8
	dp = [[inf] * (n + 1) for _ in range(n + 1)]
	dp[0][0] = 0
	for (i, a) in enumerate(alst, 1):
		for j in range(n + 1):
			dp[i][j] = dp[i - 1][j]
			if j != 0:
				dp[i][j] = max(dp[i][j], dp[i - 1][j - 1])
				if a == j:
					dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1)
	for i in range(n, k - 1, -1):
		if dp[-1][i] >= k:
			print(n - i)
			return
	print(-1)
for _ in range(int(input())):
	main()


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	(n, k) = map(int, input().split())
	A = list(map(int, input().split()))
	B = [i + 1 - A[i] for i in range(n)]
	DP = [-1] * (n + 2)
	DP[0] = 0
	for i in range(n):
		for j in range(n, -1, -1):
			if DP[j] != -1:
				DP[j + 1] = max(DP[j], DP[j + 1])
				if B[i] == j:
					DP[j] += 1
	for i in range(n + 2):
		if DP[i] >= k:
			print(i)
			break
	else:
		print(-1)


import sys
input = sys.stdin.readline

def main():
	INF = 10 ** 5
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		ar = list(map(int, input().split()))
		dp = [[0 for _ in range(n + 5)] for _ in range(n + 5)]
		ans = INF
		for i in range(1, n + 1):
			for j in range(1, i + 1):
				dp[i][j] = dp[i - 1][j]
				if ar[i - 1] == j:
					dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1)
				else:
					dp[i][j] = max(dp[i][j], dp[i - 1][j - 1])
				if dp[i][j] >= k:
					ans = min(ans, i - j)
		if ans < INF:
			print(ans)
		else:
			print(-1)
main()


import sys
input = sys.stdin.readline
al3 = list('abcdefghijklmnopqrstuvwx')
al2 = ['y', 'z']
t = int(input())
for iii in range(t):
	(n, k) = map(int, input().split())
	a = [0] + list(map(int, input().split()))
	dp = [-10 ** 18] * (n + 3) * (n + 3)

	def _(i, j):
		return i * (n + 1) + j
	dp[_(0, 0)] = 0
	for i in range(1, n + 1):
		for j in range(i + 1):
			dp[_(i, j)] = dp[_(i - 1, j)]
			if a[i] == i - j:
				dp[_(i, j)] = max(dp[_(i, j)], dp[_(i - 1, j)] + 1)
			if j >= 1:
				dp[_(i, j)] = max(dp[_(i, j)], dp[_(i - 1, j - 1)])
	ans = 10 ** 18
	for i in range(n + 1):
		if dp[_(n, i)] >= k:
			ans = min(ans, i)
	print(ans if ans < 10 ** 18 else -1)


import sys
import math
mod = 10 ** 9 + 7
LI = lambda : [int(k) for k in input().split()]
input = lambda : sys.stdin.readline().rstrip()
IN = lambda : int(input())
S = lambda : input()
r = range
from bisect import *
for t in r(IN()):
	(n, k) = LI()
	a = LI()
	ans = 10 ** 20
	dp = [[0] * (n + 1) for i in range(n + 1)]
	for i in range(n):
		dp[i + 1][0] = dp[i][0] + (a[i] == i + 1)
		if dp[i + 1][0] == k:
			print(0)
			break
	else:
		for i in range(1, n + 1):
			for j in range(1, i):
				dp[i][j] = max(dp[i - 1][j - 1], dp[i - 1][j] + (a[i - 1] == i - j))
				if dp[i][j] >= k:
					ans = min(ans, j)
		if ans == 10 ** 20:
			print(-1)
		else:
			print(ans)


def solve(A, k):
	n = len(A)
	dp = [[0] * (n + 1) for _ in range(n + 1)]
	for i in range(n):
		for l in range(1, i + 2):
			dp[i][l] = max(dp[i][l], dp[i - 1][l])
			d = 1 if A[i] == l else 0
			dp[i][l] = max(dp[i][l], dp[i - 1][l - 1] + d)
	for i in reversed(range(n + 1)):
		if dp[n - 1][i] >= k:
			return n - i
	return -1
T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split(' '))
	A = list(map(int, input().split(' ')))
	print(solve(A, k))


import os, sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd
from _collections import deque
import heapq as hp
from bisect import bisect_left, bisect_right
from math import cos, sin
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 10 ** 9 + 7
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	dp = [0] * (n + 1)
	for i in range(1, k + 1):
		ndp = [float('inf')] * (n + 1)
		for j in range(i - 1, n):
			if a[j] > j + 1:
				continue
			t1 = dp[a[j] - 1]
			if t1 == -1 or a[j] > j - t1 + 1:
				continue
			ct = j - t1 - (a[j] - 1) + t1
			ndp[a[j]] = min(ndp[a[j]], ct)
		t = float('inf')
		for j in range(n + 1):
			t = min(ndp[j], t)
			if t == float('inf'):
				dp[j] = -1
			else:
				dp[j] = t
	ans = float('inf')
	for i in ndp:
		ans = min(ans, i)
	if ans == float('inf'):
		print(-1)
	else:
		print(ans)


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

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

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	dp = [[0] * (n + 1) for __ in range(n + 1)]
	for i in range(1, n + 1):
		for j in range(0, n + 1):
			dp[i][j] = max(dp[i - 1][j] + (a[i - 1] == i - j), dp[i - 1][j - 1] if j != 0 else -100)
	ans = -1
	for j in range(n):
		if dp[-1][j] >= k:
			ans = j
			break
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	d = [0] + list(map(int, input().split()))
	dp = [-1] * (n + 1)
	dp[0] = 0
	for i in range(1, n + 1):
		for j in range(i, 0, -1):
			dp[j] = max(dp[j], dp[j - 1] + (1 if d[i] == j else 0))
	for i in range(n, 0, -1):
		if dp[i] >= k:
			print(n - i)
			break
	else:
		print(-1)


import sys
from bisect import bisect_left as lb
from collections import deque
from queue import PriorityQueue as pq
from math import *
input_ = lambda : sys.stdin.readline().strip('\r\n')
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
ap = lambda ab, bc, cd: ab[bc].append(cd)
li = lambda : list(input_())
pr = lambda x: print(x)
prinT = lambda x: print(x)
f = lambda : sys.stdout.flush()
inv = lambda x: pow(x, mod - 2, mod)
mod = 10 ** 9 + 7
for _ in range(ii()):
	(n, k) = il()
	a = il()
	dp = [[0 for i in range(n + 3)] for j in range(n + 3)]
	ans = 10 ** 10
	for i in range(1, n + 1):
		for j in range(i):
			if a[i - 1] == i - j:
				dp[i][j] = max(dp[i - 1][j] + 1, dp[i][j])
			dp[i][j] = max(dp[i - 1][j], dp[i][j])
			dp[i][j + 1] = dp[i - 1][j]
			if dp[i][j] >= k:
				ans = min(ans, j)
	if ans == 10 ** 10:
		ans = -1
	print(ans)


t = int(input())

def solve(a, n, k):
	inf = n + 2
	b = [i - x if i - x >= 0 else inf for (i, x) in enumerate(a)]
	dp = [1]
	for i in range(1, n):
		result = 0
		for j in range(i):
			if b[j] <= b[i] and i - j > b[i] - b[j]:
				result = max(result, dp[j])
		dp.append(result + 1)
	m = inf
	for i in range(n):
		if dp[i] >= k:
			m = min(m, b[i])
	return m if m < inf else -1
for test in range(t):
	(n, k) = [int(x) for x in input().split()]
	a = [int(x) - 1 for x in input().split()]
	print(solve(a, n, k))


INF = 1001001001

def main():
	(N, K) = map(int, input().split())
	A = list(map(lambda x: int(x) - 1, input().split()))
	DP = [[-INF] * (N + 1) for _ in range(N + 1)]
	DP[0][0] = 0
	for i in range(N):
		for j in range(N):
			if A[i] == j:
				DP[i + 1][j + 1] = max(DP[i + 1][j + 1], DP[i][j] + 1)
			else:
				DP[i + 1][j + 1] = max(DP[i + 1][j + 1], DP[i][j])
			DP[i + 1][j] = max(DP[i + 1][j], DP[i][j])
	Ans = INF
	for i in range(N + 1):
		if DP[N][i] >= K:
			Ans = N - i
	print(Ans if Ans != INF else -1)
T = int(input())
for _ in range(T):
	main()


import sys, io, os, math, bisect, heapq
from collections import Counter, deque, defaultdict
try:
	inp = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
except:
	inp = lambda : sys.stdin.readline().encode()
L = lambda : list(map(int, inp().split()))
I = lambda : int(inp())
S = lambda : inp().strip().decode()
C = lambda : inp().split()

def pr(a):
	print(' '.join(list(map(str, a))))

def solve():
	(n, k) = L()
	dp = [-1] * (n + 1)
	a = [0] + L()
	dp[0] = 0
	for i in range(n):
		a[i + 1] -= i + 1
		a[i + 1] = -a[i + 1]
	for i in range(1, n + 1):
		ans = -1
		for j in range(i):
			if a[j] >= 0 and a[i] - a[j] <= i - j - 1 and (a[i] >= a[j]):
				ans = max(ans, dp[j] + 1)
		dp[i] = ans
	ans = 10 ** 10
	for i in range(n + 1):
		if dp[i] >= k:
			ans = min(ans, a[i])
	if ans == 10 ** 10:
		print(-1)
	else:
		print(ans)
for _ in range(I()):
	solve()


import sys, os, io
from sys import stdin
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
	(n, k) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	dp = [[0 for i in range(n + 1)] for j in range(n + 1)]
	for i in range(1, n + 1):
		for j in range(i + 1):
			wantleft = i - a[i - 1]
			temp = 0
			if wantleft == j:
				temp = 1
			dp[i][j] = dp[i - 1][j] + temp
			if j > 0:
				dp[i][j] = max(dp[i][j], dp[i - 1][j - 1])
	res = 1000000000
	for i in range(n + 1):
		if dp[-1][i] >= k:
			res = min(res, i)
	if res == 1000000000:
		res = -1
	print(res)


import os, sys
from io import BytesIO, IOBase

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)]
inp_enu = lambda dtype: [(i, x) for (i, x) in enumerate(inp(dtype))]
inp_enus = lambda dtype, n: [[i] + inp(dtype) for i in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
for _ in range(int(input())):
	(n, k) = inp(int)
	(a, mem, ans) = (inp(int), [[-1] * (n + 1) for _ in range(n)], float('inf'))
	(mem[0][0], mem[0][1]) = (0, a[0] == 1)
	if mem[0][1] >= k:
		ans = n - 1
	for i in range(1, n):
		mem[i][0] = 0
		for j in range(1, i + 2):
			mem[i][j] = mem[i - 1][j]
			if mem[i - 1][j - 1] != -1:
				mem[i][j] = max(mem[i][j], mem[i - 1][j - 1] + (a[i] == j))
			if mem[i][j] >= k:
				ans = min(n - j, ans)
	print(ans if ans != float('inf') else -1)