#include <bits/stdc++.h>
using namespace std;
const int MAX = 200005;
set<int> S;
map<int, int> M;
int m, a[MAX], dp[MAX];
vector<int> occ[MAX], ed[MAX];
int call(int s) {
  if (dp[s] != -1) return dp[s];
  int ret = 1;
  for (int x : ed[s]) ret = max(ret, call(x) + 1);
  if (s == occ[a[s]].back() and ret == 1) {
    int v = a[s] + 1;
    if (v <= m) {
      ret += max(0, (int)(occ[v].end() -
                          upper_bound(occ[v].begin(), occ[v].end(), s)));
    }
  }
  return dp[s] = ret;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int T;
  cin >> T;
  for (int t = 1; t <= T; t++) {
    int ans = 0;
    M.clear();
    S.clear();
    int n, it = 0;
    cin >> n;
    for (int i = 1; i <= n; i++) {
      cin >> a[i];
      S.insert(a[i]);
    }
    for (int e : S) M[e] = ++it;
    for (int i = 1; i <= n; i++) a[i] = M[a[i]];
    m = it;
    for (int i = 1; i <= n; i++) occ[a[i]].push_back(i);
    for (int i = 2; i <= m; i++) {
      if (occ[i - 1].back() < occ[i][0]) {
        ed[occ[i - 1].back()].push_back(occ[i][0]);
      }
    }
    for (int i = 1; i <= m; i++) {
      ans = max(ans, (int)occ[i].size());
      for (int j = 1; j < (int)occ[i].size(); j++) {
        ed[occ[i][j - 1]].push_back(occ[i][j]);
      }
    }
    for (int i = 1; i <= n; i++) dp[i] = -1;
    for (int i = 1; i <= m; i++) {
      int v = i - 1;
      int ad;
      if (v >= 1) {
        ad =
            call(occ[i][0]) +
            max(0,
                (int)(upper_bound(occ[v].begin(), v[occ].end(), occ[i][0] - 1) -
                      occ[v].begin()));
      } else {
        ad = call(occ[i][0]);
      }
      ans = max(ans, ad);
    }
    cout << n - ans << '\n';
    for (int i = 1; i <= m; i++) occ[i].clear();
    for (int i = 1; i <= n; i++) ed[i].clear();
  }
  return 0;
}
