#include <bits/stdc++.h>
using namespace std;
const long long maxn = 2e6 + 2;
const long long maxx = 1e16;
const long long mod = 1e9 + 7;
const long long mod1 = 998244353;
long long dp[maxn];
long long dp1[maxn];
long long a[maxn];
long long nw[maxn];
long long cnt[maxn];
map<long long, long long> dd;
map<long long, long long> dd1;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long t;
  cin >> t;
  while (t--) {
    long long n;
    set<long long, greater<long long>> st;
    vector<long long> sth;
    cin >> n;
    dd.clear();
    dd1.clear();
    for (int i = 0; i <= n + 123; i++) {
      dp[i] = 0;
      dp1[i] = 0;
      cnt[i] = 0;
      nw[i] = 0;
    }
    for (int i = 1; i <= n; i++) {
      cin >> a[i];
      if (!dd[a[i]]) {
        dd[a[i]] = 1;
        sth.push_back(a[i]);
      }
    }
    sort(sth.begin(), sth.end());
    for (int i = 1; i <= sth.size(); i++) {
      dd[sth[i - 1]] = i;
    }
    for (int i = 1; i <= n; i++) {
      a[i] = dd[a[i]];
      nw[a[i]]++;
    }
    for (int i = 1; i <= n; i++) {
      long long mx = 0;
      if (dd1[a[i]]) {
        dp[a[i]]++;
        dp1[a[i]] = max(cnt[a[i] - 1] + 1, dp1[a[i]] + 1);
        if (cnt[a[i] - 1] == nw[a[i] - 1]) {
          dp1[a[i]] = max(dp[a[i] - 1] + 1, dp1[a[i]]);
        }
      } else {
        dp[a[i]] = max(cnt[a[i] - 1] + 1, dp[a[i]] + 1);
        if (cnt[a[i] - 1] == nw[a[i] - 1]) {
          dp[a[i]] = max(dp[a[i] - 1] + 1, dp[a[i]]);
        }
        dp1[a[i]] = dp[a[i]];
      }
      dd1[a[i]] = 1;
      cnt[a[i]]++;
      if (i == n) {
      }
    }
    long long mx = 0;
    for (int i = 1; i <= n; i++) {
      mx = max(mx, dp[i]);
      mx = max(mx, dp1[i]);
    }
    cout << n - mx << "\n";
  }
}
