#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const double eps = 1e-6;
const int maxn = 3e5 + 5;
int n, a[maxn];
int cnt[maxn];
int num[maxn];
int dp[maxn];
int fi[maxn];
int last[maxn];
void Solve() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    num[i] = cnt[i] = dp[i] = fi[i] = last[i] = 0;
  }
  vector<int> v(a + 1, a + 1 + n);
  sort(v.begin(), v.end());
  v.resize(unique(v.begin(), v.end()) - v.begin());
  for (int i = 1; i <= n; i++) {
    a[i] = upper_bound(v.begin(), v.end(), a[i]) - v.begin();
    num[a[i]]++;
  }
  int ans = 0;
  for (int i = 1; i <= n; i++) {
    int x = a[i];
    dp[i] = max(dp[i], cnt[x - 1] + 1);
    if (last[x]) dp[i] = max(dp[last[x]] + 1, dp[i]);
    if (cnt[x - 1] == num[x - 1])
      dp[i] = max(dp[i], dp[fi[x - 1]] + cnt[x - 1]);
    cnt[x]++;
    last[x] = i;
    if (fi[x] == 0) fi[x] = i;
    ans = max(ans, dp[i]);
  }
  cout << n - ans << "\n";
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  if (fopen(""
            ".inp",
            "r")) {
    freopen(
        ""
        ".inp",
        "r", stdin);
    freopen(
        ""
        ".out",
        "w", stdout);
  }
  int test_case = 1;
  cin >> test_case;
  while (test_case--) Solve();
  return 0;
}
