#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
int a[maxn], xi[maxn];
int dp[maxn], fir[maxn], last[maxn], num[maxn], sum[maxn];
int n, cntX;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int T;
  cin >> T;
  while (T--) {
    cin >> n;
    for (int i = 1; i <= n; ++i) {
      dp[i] = fir[i] = last[i] = num[i] = sum[i] = 0;
    }
    cntX = 0;
    for (int i = 1; i <= n; ++i) {
      cin >> a[i];
      xi[++cntX] = a[i];
    }
    sort(xi + 1, xi + 1 + cntX);
    cntX = unique(xi + 1, xi + 1 + cntX) - xi - 1;
    for (int i = 1; i <= n; ++i) {
      a[i] = lower_bound(xi + 1, xi + 1 + cntX, a[i]) - xi;
      ++sum[a[i]];
    }
    for (int i = n; i >= 1; --i) {
      fir[a[i]] = i;
    }
    for (int i = 1; i <= n; ++i) {
      dp[i] = max(dp[last[a[i]]], num[a[i] - 1]) + 1;
      if (num[a[i] - 1] == sum[a[i] - 1]) {
        dp[i] = max(dp[i], dp[fir[a[i] - 1]] + sum[a[i] - 1]);
      }
      ++num[a[i]];
      last[a[i]] = i;
    }
    cout << n - *max_element(dp + 1, dp + 1 + n) << "\n";
  }
  return 0;
}
