#include <bits/stdc++.h>
using namespace std;
using lint = long long;
const lint linf = 1e18 + 7;
const lint inf = 1e9 + 7;
const int MOD = 1000000007;
void press(vector<long long>& x) {
  map<int, int> memo;
  int n = x.size();
  for (int i = 0; i < n; ++i) {
    memo[x[i]] += 1;
  }
  int cur = 1;
  for (auto& val : memo) {
    val.second = cur;
    ++cur;
  }
  for (int i = 0; i < n; ++i) {
    x[i] = memo[x[i]];
  }
}
void solve() {
  int n;
  cin >> n;
  vector<lint> a(n, 0);
  for (int i = 0; i < n; ++i) cin >> a[i];
  auto b = a;
  press(b);
  vector<vector<int>> dp(n + 5, vector<int>(3, 0));
  vector<int> cnt(n + 5, 0);
  for (int i = 0; i < n; ++i) cnt[b[i]] += 1;
  int res = n - 1;
  for (int i = 0; i < n; ++i) {
    if (dp[b[i]][0] == 0) {
      dp[b[i]][0] = max(dp[b[i] - 1][1], dp[b[i] - 1][2]) + 1;
    }
    if (dp[b[i]][1] + 1 < cnt[b[i]]) {
      ++dp[b[i]][1];
    } else {
      dp[b[i]][2] = dp[b[i]][0] + dp[b[i]][1];
      dp[b[i]][1] += 1;
    }
    int hoge = dp[b[i]][1] + cnt[b[i] + 1] - dp[b[i] + 1][1];
    res = min(res, n - hoge);
    hoge = cnt[b[i]] - dp[b[i]][1] + dp[b[i] - 1][2] + 1;
    res = min(res, n - hoge);
  }
  for (int i = 1; i <= n; ++i) {
    for (int j = 0; j < 3; ++j) {
      res = min(res, n - dp[i][j]);
    }
  }
  cout << res << "\n";
}
signed main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int t;
  cin >> t;
  for (int i = 0; i < t; ++i) {
    solve();
  }
  return 0;
}
