#include <bits/stdc++.h>
using namespace std;
#pragma GCC target("avx2")
#pragma GCC optimization("O3")
#pragma GCC optimization("unroll-loops")
const int INF = 1e9 + 23;
const long long INFL = 2e18 + 23;
inline void solve() {
  int n;
  cin >> n;
  vector<int> a(n + 1);
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  vector<int> temp;
  for (int i = 1; i <= n; i++) temp.push_back(a[i]);
  sort(temp.begin(), temp.end());
  temp.erase(unique(temp.begin(), temp.end()), temp.end());
  for (int i = 1; i <= n; i++)
    a[i] = lower_bound(temp.begin(), temp.end(), a[i]) - temp.begin() + 1;
  vector<int> dp(n + 1, 0), last(n + 1, 0);
  vector<int> cnt(n + 1, 0), tot(n + 1, 0);
  vector<int> st(n + 1, 0);
  int ans = 0;
  for (int i = 1; i <= n; i++) {
    if (st[a[i]] == 0) st[a[i]] = i;
    tot[a[i]]++;
  }
  for (int i = 1; i <= n; i++) {
    int x = a[i];
    dp[i] = 1 + dp[last[x]];
    dp[i] = max(dp[i], 1 + cnt[x - 1]);
    if (cnt[x - 1] == tot[x - 1]) {
      dp[i] = max(dp[i], 1 + dp[st[x - 1]] + cnt[x - 1] - 1);
    }
    ans = max(ans, dp[i]);
    last[x] = i;
    cnt[x]++;
  }
  cout << n - ans << "\n";
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int tc;
  cin >> tc;
  for (int nc = 1; nc <= tc; nc++) {
    solve();
  }
  return 0;
}
