#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 5;
int n;
int a[MAXN];
int b[MAXN];
int firstDp[MAXN], dp[MAXN], numCnt[MAXN], numDemand[MAXN];
void init() {
  for (int i = 0; i <= n; i++) {
    dp[i] = 0;
    numCnt[i] = 0;
    firstDp[i] = 0;
    numDemand[i] = 0;
  }
  set<int> s;
  map<int, int> code;
  for (int i = 0; i < n; i++) {
    s.insert(a[i]);
  }
  int ind = 0;
  for (auto it = s.begin(); it != s.end(); it++) code[*it] = ind, ind++;
  for (int i = 0; i < n; i++) a[i] = code[a[i]], b[i] = a[i], numDemand[a[i]]++;
  sort(b, b + n);
}
void solveTestcase() {
  cin >> n;
  for (int i = 0; i < n; i++) cin >> a[i];
  init();
  for (int i = 0; i < n; i++) {
    bool isFirst = (dp[a[i]] == 0);
    dp[a[i]]++;
    if (a[i] != 0) {
      dp[a[i]] = max(dp[a[i]], numCnt[a[i] - 1] + 1);
      if (numCnt[a[i] - 1] == numDemand[a[i] - 1])
        dp[a[i]] =
            max(dp[a[i]], firstDp[a[i] - 1] + numDemand[a[i] - 1] - 1 + 1);
    }
    numCnt[a[i]]++;
    if (isFirst == true) firstDp[a[i]] = dp[a[i]];
  }
  int answer = 0;
  for (int i = 0; i < n; i++) answer = max(answer, dp[i]);
  cout << n - answer << '\n';
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  int T;
  cin >> T;
  while (T--) solveTestcase();
}
