#include <bits/stdc++.h>   using namespace std;   #pragma warning(disable : 4996)   const long double PI = 3.14159265358979323846;   const long long MOD = 998244353;   mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());   void solve() {     int n;     cin >> n;     vector<int> a(n);     map<int, deque<int>> d;     vector<int> b;     for (int i = 0; i < n; i++) {       cin >> a[i];       b.push_back(a[i]);     }     sort(b.begin(), b.end());     b.resize(unique(b.begin(), b.end()) - b.begin());     for (int i = 0; i < n; i++) {       a[i] = lower_bound(b.begin(), b.end(), a[i]) - b.begin();       d[a[i]].push_back(i);     }     map<int, int> dp;     int ans = 0;     for (auto c : d) {       dp[c.first] = d[c.first].size();       if (!d[c.first - 1].empty() && d[c.first - 1].back() < d[c.first].front()) {         dp[c.first] = max(dp[c.first], dp[c.first - 1] + (int)d[c.first].size());       }       int cnt = 0;       for (auto kek : d[c.first - 1]) {         if (kek < d[c.first].front()) {           cnt++;         }       }       dp[c.first] = max(dp[c.first], cnt + (int)d[c.first].size());       ans = max(ans, dp[c.first]);       int ret = 0;       for (auto kek : d[c.first]) {         if (!d[c.first - 1].empty() && kek > d[c.first - 1].back()) {           ret++;         }       }       ans = max(ans, dp[c.first - 1] + ret);       vector<pair<int, int>> arr;       for (auto d : d[c.first - 1]) {         arr.push_back({d, 0});       }       for (auto d : d[c.first]) {         arr.push_back({d, 1});       }       sort(arr.begin(), arr.end());       int dp0 = 0, dp1 = 0;       for (auto c : arr) {         if (c.second == 1) {           dp1++;         } else {           dp0++;           dp1 = max(dp1, dp0);         }       }       ans = max(ans, dp1);     }     cout << n - ans <<   n ;   }   int main() {     srand(time(0));     ios_base::sync_with_stdio(false);     cin.tie(0);     int q;     cin >> q;     while (q--) solve();   }   