#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n, m, a[N];
vector<int> g[N];
struct interval_weights
{
int root[N], tot, last[N];
struct Node
{
int l, r;
int cnt;
} tr[N * 40];
int build(int l, int r)
{
int p = ++tot;
if (l == r) return p;
int mid = (l + r) >> 1;
tr[p].l = build(l, mid), tr[p].r = build(mid + 1, r);
return p;
}
int insert(int p, int idx, int l, int r, int x)
{
int q = ++tot;
tr[q] = tr[p], tr[q].cnt += x;
if (l < r)
{
int mid = (l + r) >> 1;
if (idx <= mid) tr[q].l = insert(tr[p].l, idx, l, mid, x);
else tr[q].r = insert(tr[p].r, idx, mid + 1, r, x);
}
return q;
}
int query(int idx, int q, int l, int r)
{
if (l == r) return tr[q].cnt;
int mid = (l + r) >> 1;
if (idx <= mid) return query(idx, tr[q].l, l, mid) + tr[tr[q].r].cnt;
else return query(idx, tr[q].r, mid + 1, r);
}
int ask(int l, int r)
{
return query(l, s.root[r], 1, n);
}
void init(int n)
{
root[0] = build(1, n);
for (int i = 1; i <= n; i++)
{
if (!last[a[i]]) // 该数据第一次出现
root[i] = insert(root[i - 1], i, 1, n, 1);
else
{
int t = insert(root[i - 1], last[a[i]], 1, n, -1);
root[i] = insert(t, i, 1, n, 1);
}
last[a[i]] = i;
}
}
void clear(int n)
{
for (int i = 1; i <= n; i++)
{
root[i] = 0;
last[a[i]] = 0;
}
for (int i = 0; i <= tot; i++) tr[i] = {0, 0, 0};
tot = 0;
}
}s;
void solve()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
g[a[i]].push_back(i);
}
s.init(n);
int ans = -1;
for (int i = 1; i <= min(n + 1, m); i++)
{
g[i].push_back(0);
g[i].push_back(n + 1);
sort(g[i].begin(), g[i].end());
for (int j = 1; j < (int)g[i].size(); j++)
{
int l = g[i][j - 1] + 1, r = g[i][j] - 1;
if (l > r) continue;
ans = max(ans, s.ask(l, r) - i);
}
g[i].clear();
}
s.clear(n);
cout << ans << '\n';
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int T; cin >> T;
while (T--) solve();
return 0;
}