#include <bits/stdc++.h>
#define For(i,x,y) for(int i=x; i<y; ++i)
#define mem(x,y) memset(x,y,sizeof(x))
#define PII pair<int,int>
#define INF 0x3f3f3f3f
#define ll long long
#define maxn 1005
#define se second
#define fi first
#define endl '\n'
using namespace std;
const int N=3e5+105;
int vis[N],a[N];
int main(){
    int q;
    cin>>q;
    while(q--){
        int n,mini=N,maxi=0;
        cin>>n;
        For(i,0,n) cin>>a[i];
        mem(vis,0);
        int cnt=0,cnt1=0;
        For(i,0,n){
            if(a[i]<maxi){
                if(!vis[a[i]])
                ++cnt,vis[a[i]]=1;
            }
            maxi=max(maxi,a[i]);
        }
        mem(vis,0);
        for(int i=n-1; i>=0; --i){
            if(a[i]>mini){
                if(!vis[a[i]])
                ++cnt1,vis[a[i]]=1;
            }
            mini=min(mini,a[i]);
        }
        cout<<min(cnt,cnt1)<<endl;
    }
    // system("pause");
    return 0;
}


#include <bits/stdc++.h>
#define For(i,x,y) for(int i=x; i<y; ++i)
#define mem(x,y) memset(x,y,sizeof(x))
#define PII pair<int,int>
#define INF 0x3f3f3f3f
#define ll long long
#define maxn 1005
#define se second
#define fi first
#define endl '\n'
using namespace std;
const int N=3e5+105;
int vis[N],a[N];
int main(){
    int q;
    cin>>q;
    map<int,int>ma;
    while(q--){
        int n,mini=N,maxi=0;
        cin>>n;
        For(i,0,n) cin>>a[i];
        ma.clear();
        int cnt=0,cnt1=0;
        For(i,0,n){
            if(a[i]<maxi){
                if(ma[a[i]]<1)
                ++cnt,ma[a[i]]=1;
            }
            maxi=max(maxi,a[i]);
        }
        ma.clear();
        for(int i=n-1; i>=0; --i){
            if(a[i]>mini){
                if(ma[a[i]]<1)
                ++cnt1,ma[a[i]]=1;
            }
            mini=min(mini,a[i]);
        }
        cout<<min(cnt,cnt1)<<endl;
    }
    // system("pause");
    return 0;
}


#include <bits/stdc++.h>
#define For(i,x,y) for(int i=x; i<y; ++i)
#define mem(x,y) memset(x,y,sizeof(x))
#define PII pair<int,int>
#define INF 0x3f3f3f3f
#define ll long long
#define maxn 1005
#define se second
#define fi first
#define endl '\n'
using namespace std;
const int N=3e5+105;
int a[N],b[N],n,dp[N];
vector<int>edge[N];
void solve(){
    sort(b+1,b+n+1);
    int nb=unique(b+1,b+n+1)-b-1;
    int ans=1;
    dp[1]=1;
    For(i,1,nb){
        int x=b[i],y=b[i+1];
        if(edge[x].back()<edge[y][0])dp[i+1]=dp[i]+1;
        else dp[i+1]=1;
        ans=max(ans,dp[i+1]);
    }
    cout<<nb-ans<<endl;
}
int main(){
    int t;
    cin>>t;
    while(t--){
        cin>>n;
        For(i,1,n+1) cin>>a[i],b[i]=a[i],edge[a[i]].push_back(i);
        solve();
        For(i,1,n+1) edge[a[i]].clear();
    }
    // system("pause");
    return 0;
}


#include <bits/stdc++.h>
#define For(i,x,y) for(int i=x; i<y; ++i)
#define mem(x,y) memset(x,y,sizeof(x))
#define PII pair<int,int>
#define INF 0x3f3f3f3f
#define ll long long
#define maxn 1005
#define se second
#define fi first
#define endl '\n'
using namespace std;
const int N=3e5+105;
int a[N],b[N],n,dp[N];
vector<int>edge[N];
void solve(){
    sort(b,b+n);
    int nb=unique(b,b+n)-b;
    int ans=1;
    dp[0]=1;
    For(i,0,nb){
        int x=b[i],y=b[i+1];
        if(edge[x].back()<edge[y][0])dp[i+1]=dp[i]+1;
        else dp[i+1]=1;
        ans=max(ans,dp[i+1]);
    }
    cout<<nb-ans<<endl;
}
int main(){
    int t;
    cin>>t;
    while(t--){
        cin>>n;
        For(i,0,n) cin>>a[i],b[i]=a[i],edge[a[i]].push_back(i);
        solve();
        For(i,0,n) edge[a[i]].clear();
    }
    // system("pause");
    return 0;
}


#include <cstdio>
#define Max(a, b) (a > b ? a : b)
const int N = (int)3e5+10, inf = (int)1e8;

int q;
int n, a;
int l[N], r[N];

inline int read()
{
    int x = 0; char ch = getchar();
    for(; ch > '9' || ch < '0'; ch = getchar());
    for(; ch >= '0' && ch <= '9'; ch = getchar()) x = (x<<1)+(x<<3)+ch-48;
    return x;
}

int main()
{
    q = read();
    while(q--)
    {
        n = read();
        for(int i = 1; i <= n; ++i) l[i] = inf;
        for(int i = 1; i <= n; ++i)
        {
            a = read();
            if(l[a] == inf) l[a] = i;
            r[a] = i;
        }

        int M = 0, cnt = 0, las = 0, tmp = 0;
        for(int i = 1; i <= n; ++i)
        {
            if(l[i] != inf)
            {
                ++cnt;
                if(r[las] <= l[i]) ++tmp;
                else
                {
                    M = Max(tmp, M);
                    tmp = 1;
                }
                las = i;
            }
        }

        printf("%d\n",cnt - Max(M, tmp));
    }
    return 0;
}


#include <cstdio>
#define Max(a, b) (a > b ? a : b)
const int N = (int)3e5+10, inf = (int)1e8;

int q;
int n, a;
int l[N], r[N], que[N];

inline int read()
{
    int x = 0; char ch = getchar();
    for(; ch > '9' || ch < '0'; ch = getchar());
    for(; ch >= '0' && ch <= '9'; ch = getchar()) x = (x<<1)+(x<<3)+ch-48;
    return x;
}

int main()
{
    q = read();
    while(q--)
    {
        n = read();
        for(int i = 1; i <= n; ++i) l[i] = inf;
        for(int i = 1; i <= n; ++i)
        {
            a = read();
            if(l[a] == inf) l[a] = i;
            r[a] = i;
        }
        que[0] = 0;

        int M = 0, cnt = 0;
        for(int i = 1; i <= n; ++i)
        {
            if(l[i] != inf)
            {
                ++cnt;
                if(r[que[que[0]]] <= l[i]) que[++que[0]] = i;
                else
                {
                    M = Max(que[0], M);
                    while(r[que[--que[0]]] > l[i]) if(!que[0]) break;
                    que[++que[0]] = i;
                }
            }
        }

        printf("%d\n",cnt - Max(M, que[0]));
    }
    return 0;
}


#include <cstdio>
#define Max(a, b) (a > b ? a : b)
const int N = (int)3e5+10, inf = (int)1e8;

int q;
int n, a;
int l[N], r[N];

inline int read()
{
    int x = 0; char ch = getchar();
    for(; ch > '9' || ch < '0'; ch = getchar());
    for(; ch >= '0' && ch <= '9'; ch = getchar()) x = (x<<1)+(x<<3)+(ch^48);
    return x;
}

int main()
{
    q = read();
    while(q--)
    {
        n = read();
        for(int i = 1; i <= n; ++i) l[i] = inf;
        for(int i = 1; i <= n; ++i)
        {
            a = read();
            if(l[a] == inf) l[a] = i;
            r[a] = i;
        }

        int M = 0, cnt = 0, las = 0, tmp = 0;
        for(int i = 1; i <= n; ++i)
        {
            if(l[i] != inf)
            {
                ++cnt;
                if(r[las] <= l[i]) ++tmp;
                else
                {
                    if(tmp > M) M = tmp;
                    tmp = 1;
                }
                las = i;
            }
        }

        printf("%d\n",cnt - Max(M, tmp));
    }
    return 0;
}


#include <cstdio>
#define Max(a, b) (a > b ? a : b)
const int N = (int)3e5+10, inf = (int)1e8;

int q;
int n, a;
int l[N], r[N], que[N];

inline int read()
{
    int x = 0; char ch = getchar();
    for(; ch > '9' || ch < '0'; ch = getchar());
    for(; ch >= '0' && ch <= '9'; ch = getchar()) x = (x<<1)+(x<<3)+ch-48;
    return x;
}

int main()
{
    q = read();
    while(q--)
    {
        n = read();
        for(int i = 1; i <= n; ++i) l[i] = inf;
        for(int i = 1; i <= n; ++i)
        {
            a = read();
            if(l[a] == inf) l[a] = i;
            r[a] = i;
        }
        que[0] = 0;

        int M = 0, cnt = 0, las = 0, tmp = 0;
        for(int i = 1; i <= n; ++i)
        {
            if(l[i] != inf)
            {
                ++cnt;
                if(r[las] <= l[i]) ++tmp;
                else
                {
                    M = Max(tmp, M);
                    tmp = 1;
                }
                las = i;
            }
        }

        printf("%d\n",cnt - Max(M, tmp));
    }
    return 0;
}


#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;

#define     LL                      long long int
#define     LD                      long double
#define     ULL                     unsigned long long int

#define     pii                     pair<int, int>
#define     ump                     unordered_map
#define     mp                      make_pair
#define     mt                      make_tuple
#define     pb                      push_back
#define     ff                      first
#define     ss                      second
#define     SZ(x)                   (int)x.size()
#define     all(x)                  x.begin(), x.end()
#define     lb(x, y)                lower_bound(all(x), y)
#define     fill2d(arr, a, b, v)    fill(&arr[0][0], &arr[0][0] + a * b, v)
#define     fill3d(arr, a, b, c, v) fill(&arr[0][0], &arr[0][0] + a * b * c, v)
#define     rep(i, begin, end)      for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))

#define     sp(x)                   setprecision(x) << fixed
#define     what_is(x)              cout << #x << " is " << x << endl
//#define     I64                     ll

#define     PI                      acos(-1.0)
#define     EPS                     1e-12
#define     mx                      200010
#define     S_SIZE                  2000010

const LL inf = 1000000000;
const LL mod = 1000000000 + 7;

inline void IO() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); }
inline int dcmp (LD x) { return x < -EPS ? -1 : (x > EPS); }

template<class T> inline int CHECK(T MASK, int i) { return (MASK >> i) & 1; }
template<class T> inline T ON(T MASK, int i) { return MASK | (T(1) << i); }
template<class T> inline T OFF(T MASK, int i) { return MASK & (~(T(1) << i)); }
template<typename T> inline int CNT(T MASK) {
    if (numeric_limits<T>::digits <= numeric_limits<unsigned int>::digits) return __builtin_popcount(MASK);
    else return __builtin_popcountll(MASK);
}
template<class T> inline int RIGHT(T MASK) { return log2(MASK & -MASK); }

int dx4[] = { 0, 0, -1, +1 }; int dy4[] = { +1, -1, 0, 0 };
int dx8[] = { 1, 1, 0, -1, -1, -1, 0, 1, 0 }; int dy8[] = { 0, 1, 1, 1, 0, -1, -1, -1, 0 };

inline void I(int& a) { scanf("%d", &a); } inline void I(LL& a) { scanf("%I64d", &a); }
inline void I(ULL& a) { scanf("%I64u", &a); } inline void I(char* a) { scanf("%s", a); }
char Iarr[S_SIZE]; inline void I(string& a) { scanf("%s", Iarr); a = Iarr; }
template<typename T, typename... Args>
void I(T& a, Args&... args) { I(a); I(args...); }

inline void OUT(int a) { printf("%d", a); } inline void OUT(LL a) { printf("%I64d", a); }
inline void OUT(const char* a) { printf("%s", a); } inline void OUT(char* a) { printf("%s", a); }
inline void OUT(bool a) { printf("%d", a); } inline void OUT(string a) { rep(it, a.begin(), a.end()) printf("%c", *it); }
inline void OUT(ULL a) { printf("%I64u", a); }
template<typename T, typename... Args>
void OUT(T a, Args... args) { OUT(a); OUT(" "); OUT(args...); }
template<typename... Args>
void O(Args... args) { OUT(args...); OUT("\n"); }

template<typename T1, typename T2>
inline ostream& operator<<(ostream& os, pair<T1, T2> p) { os << "{" << p.first << ", " << p.second << "}"; return os; }
template<typename T>
inline ostream& operator<<(ostream& os, vector<T>& a) { os << "["; for (int i = 0; i < (int)a.size(); i++) { if (i) os << ", "; os << a[i]; } os << "]"; return os; }

#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
	cout << *it << " = " << a << endl;
	err(++it, args...);
}

// mp.reserve(1024); mp.max_load_factor(0.25);
// head

const int M = 300010; // maximum number of cubes

set<pii> st;
vector<int> pos[M];
int n;

void clr()
{
    st.clear();
    for (int i = 0; i <= n; i++) {
        pos[i].clear();
    }
}

int main()
{
    int q;
    I(q);
    while (q--) {
        clr();
        int nn;
        I(nn);
        int a[nn];
        set<int> stt;
        for (int i = 0; i < nn; i++) {
            I(a[i]);
            stt.insert(a[i]);
        }
        vector<int> vt;
        for (int x : stt) {
            vt.push_back(x);
        }
        for (int i = 0; i < nn; i++) {
            auto it = lower_bound(all(vt), a[i]);
            int p = it - vt.begin();
            p++;
            a[i] = p;
        }
        for (int i = 0; i < nn; i++) {
            pos[a[i]].pb(i);
        }
        n = SZ(vt);
        int curr = -1;
        bool ok = 1;
        for (int i = n; i >= 1; i--) {
            for (int x : pos[i]) {
                st.insert(mp(x, i));
                auto it = st.find(mp(x, i));
                if (it != st.begin()) {
                    it--;
                    if (it->second > i) ok = 0;
                    it++;
                }
                it++;
                if (it != st.end()) {
                    if (it->second < i) ok = 0;
                }
                if (!ok) {
                    curr = i;
                    break;
                }
            }
            if (!ok) {
                for (int x : pos[i]) {
                    st.erase(mp(x, i));
                }
                i = 0;
            }
        }
        if (curr == -1) {
            O(0);
        }
        else {
            int ans = curr;
            int last = n;
            while (curr != -1) {
                for (int i = last; i >= curr; i--) {
                    for (int x : pos[i]) {
                        st.erase(mp(x, i));
                    }
                }
                last = curr - 1;
                if (curr == 1)
                    curr = -1;
                while (curr != -1) {
                    curr--;
                    ok = 1;
                    for (int x : pos[curr]) {
                        st.insert(mp(x, curr));
                        auto it = st.find(mp(x, curr));
                        if (it != st.begin()) {
                            it--;
                            if (it->second > curr) ok = 0;
                            it++;
                        }
                        it++;
                        if (it != st.end()) {
                            if (it->second < curr) ok = 0;
                        }
                        if (!ok) {
                            break;
                        }
                    }
                    if (!ok) {
                        for (int x : pos[curr]) {
                            st.erase(mp(x, curr));
                        }
                        break;
                    }
                    else if (curr == 1) curr = -1;
                }
                int temp = n - last;
                if (curr != -1) temp += curr;
                ans = min(ans, temp);
            }
            O(ans);
        }
    }

    return 0;
}


#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;

#define     LL                      long long int
#define     LD                      long double
#define     ULL                     unsigned long long int

#define     pii                     pair<int, int>
#define     ump                     unordered_map
#define     mp                      make_pair
#define     mt                      make_tuple
#define     pb                      push_back
#define     ff                      first
#define     ss                      second
#define     SZ(x)                   (int)x.size()
#define     all(x)                  x.begin(), x.end()
#define     lb(x, y)                lower_bound(all(x), y)
#define     fill2d(arr, a, b, v)    fill(&arr[0][0], &arr[0][0] + a * b, v)
#define     fill3d(arr, a, b, c, v) fill(&arr[0][0], &arr[0][0] + a * b * c, v)
#define     rep(i, begin, end)      for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))

#define     sp(x)                   setprecision(x) << fixed
#define     what_is(x)              cout << #x << " is " << x << endl
//#define     I64                     ll

#define     PI                      acos(-1.0)
#define     EPS                     1e-12
#define     mx                      200010
#define     S_SIZE                  2000010

const LL inf = 1000000000;
const LL mod = 1000000000 + 7;

inline void IO() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); }
inline int dcmp (LD x) { return x < -EPS ? -1 : (x > EPS); }

template<class T> inline int CHECK(T MASK, int i) { return (MASK >> i) & 1; }
template<class T> inline T ON(T MASK, int i) { return MASK | (T(1) << i); }
template<class T> inline T OFF(T MASK, int i) { return MASK & (~(T(1) << i)); }
template<typename T> inline int CNT(T MASK) {
    if (numeric_limits<T>::digits <= numeric_limits<unsigned int>::digits) return __builtin_popcount(MASK);
    else return __builtin_popcountll(MASK);
}
template<class T> inline int RIGHT(T MASK) { return log2(MASK & -MASK); }

int dx4[] = { 0, 0, -1, +1 }; int dy4[] = { +1, -1, 0, 0 };
int dx8[] = { 1, 1, 0, -1, -1, -1, 0, 1, 0 }; int dy8[] = { 0, 1, 1, 1, 0, -1, -1, -1, 0 };

inline void I(int& a) { scanf("%d", &a); } inline void I(LL& a) { scanf("%I64d", &a); }
inline void I(ULL& a) { scanf("%I64u", &a); } inline void I(char* a) { scanf("%s", a); }
char Iarr[S_SIZE]; inline void I(string& a) { scanf("%s", Iarr); a = Iarr; }
template<typename T, typename... Args>
void I(T& a, Args&... args) { I(a); I(args...); }

inline void OUT(int a) { printf("%d", a); } inline void OUT(LL a) { printf("%I64d", a); }
inline void OUT(const char* a) { printf("%s", a); } inline void OUT(char* a) { printf("%s", a); }
inline void OUT(bool a) { printf("%d", a); } inline void OUT(string a) { rep(it, a.begin(), a.end()) printf("%c", *it); }
inline void OUT(ULL a) { printf("%I64u", a); }
template<typename T, typename... Args>
void OUT(T a, Args... args) { OUT(a); OUT(" "); OUT(args...); }
template<typename... Args>
void O(Args... args) { OUT(args...); OUT("\n"); }

template<typename T1, typename T2>
inline ostream& operator<<(ostream& os, pair<T1, T2> p) { os << "{" << p.first << ", " << p.second << "}"; return os; }
template<typename T>
inline ostream& operator<<(ostream& os, vector<T>& a) { os << "["; for (int i = 0; i < (int)a.size(); i++) { if (i) os << ", "; os << a[i]; } os << "]"; return os; }

#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
	cout << *it << " = " << a << endl;
	err(++it, args...);
}

// mp.reserve(1024); mp.max_load_factor(0.25);
// head

const int M = 300010; // maximum number of cubes

set<pii> st;
vector<int> pos[M];
int n;

void clr()
{
    st.clear();
    for (int i = 0; i <= n; i++) {
        pos[i].clear();
    }
}

int main()
{
    int q;
    I(q);
    while (q--) {
        clr();
        int nn;
        I(nn);
        int a[nn];
        set<int> stt;
        for (int i = 0; i < nn; i++) {
            I(a[i]);
            stt.insert(a[i]);
        }
        vector<int> vt;
        for (int x : stt) {
            vt.push_back(x);
        }
        for (int i = 0; i < nn; i++) {
            auto it = lower_bound(all(vt), a[i]);
            int p = it - vt.begin();
            p++;
            a[i] = p;
        }
        for (int i = 0; i < nn; i++) {
            pos[a[i]].pb(i);
        }
        n = SZ(vt);
        int curr = -1;
        bool ok = 1;
        for (int i = n; i >= 1; i--) {
            for (int x : pos[i]) {
                st.insert(mp(x, i));
                auto it = st.find(mp(x, i));
                if (it != st.begin()) {
                    it--;
                    if (it->second > i) ok = 0;
                    it++;
                }
                it++;
                if (it != st.end()) {
                    if (it->second < i) ok = 0;
                }
                if (!ok) {
                    curr = i;
                    break;
                }
            }
            if (!ok) {
                for (int x : pos[i]) {
                    st.erase(mp(x, i));
                }
                i = 0;
            }
        }
        if (curr == -1) {
            O(0);
        }
        else {
            int ans = curr;
            int last = n;
            while (curr != -1) {
                for (int i = last; i >= curr; i--) {
                    for (int x : pos[i]) {
                        st.erase(mp(x, i));
                    }
                }
                last = curr - 1;
                if (curr == 1)
                    curr = -1;
                while (curr != -1) {
                    curr--;
                    ok = 1;
                    for (int x : pos[curr]) {
                        st.insert(mp(x, curr));
                        auto it = st.find(mp(x, curr));
                        if (it != st.begin()) {
                            it--;
                            if (it->second > curr) ok = 0;
                            it++;
                        }
                        it++;
                        if (it != st.end()) {
                            if (it->second < curr) ok = 0;
                        }
                        if (!ok) {
                            break;
                        }
                    }
                    if (!ok) {
                        for (int x : pos[curr]) {
                            st.erase(mp(x, curr));
                        }
                        break;
                    }
                    else if (curr == 1) curr = -1;
                }
            }
            int temp = n - last;
            if (curr != -1) temp += curr;
            ans = min(ans, temp);
            O(ans);
        }
    }

    return 0;
}


#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;

#define     LL                      long long int
#define     LD                      long double
#define     ULL                     unsigned long long int

#define     pii                     pair<int, int>
#define     ump                     unordered_map
#define     mp                      make_pair
#define     mt                      make_tuple
#define     pb                      push_back
#define     ff                      first
#define     ss                      second
#define     SZ(x)                   (int)x.size()
#define     all(x)                  x.begin(), x.end()
#define     lb(x, y)                lower_bound(all(x), y)
#define     fill2d(arr, a, b, v)    fill(&arr[0][0], &arr[0][0] + a * b, v)
#define     fill3d(arr, a, b, c, v) fill(&arr[0][0], &arr[0][0] + a * b * c, v)
#define     rep(i, begin, end)      for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))

#define     sp(x)                   setprecision(x) << fixed
#define     what_is(x)              cout << #x << " is " << x << endl
//#define     I64                     ll

#define     PI                      acos(-1.0)
#define     EPS                     1e-12
#define     mx                      200010
#define     S_SIZE                  2000010

const LL inf = 1000000000;
const LL mod = 1000000000 + 7;

inline void IO() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); }
inline int dcmp (LD x) { return x < -EPS ? -1 : (x > EPS); }

template<class T> inline int CHECK(T MASK, int i) { return (MASK >> i) & 1; }
template<class T> inline T ON(T MASK, int i) { return MASK | (T(1) << i); }
template<class T> inline T OFF(T MASK, int i) { return MASK & (~(T(1) << i)); }
template<typename T> inline int CNT(T MASK) {
    if (numeric_limits<T>::digits <= numeric_limits<unsigned int>::digits) return __builtin_popcount(MASK);
    else return __builtin_popcountll(MASK);
}
template<class T> inline int RIGHT(T MASK) { return log2(MASK & -MASK); }

int dx4[] = { 0, 0, -1, +1 }; int dy4[] = { +1, -1, 0, 0 };
int dx8[] = { 1, 1, 0, -1, -1, -1, 0, 1, 0 }; int dy8[] = { 0, 1, 1, 1, 0, -1, -1, -1, 0 };

inline void I(int& a) { scanf("%d", &a); } inline void I(LL& a) { scanf("%I64d", &a); }
inline void I(ULL& a) { scanf("%I64u", &a); } inline void I(char* a) { scanf("%s", a); }
char Iarr[S_SIZE]; inline void I(string& a) { scanf("%s", Iarr); a = Iarr; }
template<typename T, typename... Args>
void I(T& a, Args&... args) { I(a); I(args...); }

inline void OUT(int a) { printf("%d", a); } inline void OUT(LL a) { printf("%I64d", a); }
inline void OUT(const char* a) { printf("%s", a); } inline void OUT(char* a) { printf("%s", a); }
inline void OUT(bool a) { printf("%d", a); } inline void OUT(string a) { rep(it, a.begin(), a.end()) printf("%c", *it); }
inline void OUT(ULL a) { printf("%I64u", a); }
template<typename T, typename... Args>
void OUT(T a, Args... args) { OUT(a); OUT(" "); OUT(args...); }
template<typename... Args>
void O(Args... args) { OUT(args...); OUT("\n"); }

template<typename T1, typename T2>
inline ostream& operator<<(ostream& os, pair<T1, T2> p) { os << "{" << p.first << ", " << p.second << "}"; return os; }
template<typename T>
inline ostream& operator<<(ostream& os, vector<T>& a) { os << "["; for (int i = 0; i < (int)a.size(); i++) { if (i) os << ", "; os << a[i]; } os << "]"; return os; }

#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
	cout << *it << " = " << a << endl;
	err(++it, args...);
}

// mp.reserve(1024); mp.max_load_factor(0.25);
// head

const int M = 300010; // maximum number of cubes

set<pii> st;
vector<int> pos[M];
int n;

void clr()
{
    st.clear();
    for (int i = 0; i <= n; i++) {
        pos[i].clear();
    }
}

int main()
{
    int q;
    I(q);
    while (q--) {
        clr();
        int nn;
        I(nn);
        int a[nn];
        set<int> stt;
        for (int i = 0; i < nn; i++) {
            I(a[i]);
            stt.insert(a[i]);
        }
        vector<int> vt;
        for (int x : stt) {
            vt.push_back(x);
        }
        for (int i = 0; i < nn; i++) {
            auto it = lower_bound(all(vt), a[i]);
            int p = it - vt.begin();
            p++;
            a[i] = p;
        }
        for (int i = 0; i < nn; i++) {
            pos[a[i]].pb(i);
        }
        n = SZ(vt);
        int curr = -1;
        bool ok = 1;
        for (int i = n; i >= 1; i--) {
            for (int x : pos[i]) {
                st.insert(mp(x, i));
                auto it = st.find(mp(x, i));
                if (it != st.begin()) {
                    it--;
                    if (it->second > i) ok = 0;
                    it++;
                }
                it++;
                if (it != st.end()) {
                    if (it->second < i) ok = 0;
                }
                if (!ok) {
                    curr = i;
                    break;
                }
            }
            if (!ok) {
                for (int x : pos[i]) {
                    st.erase(mp(x, i));
                }
                i = 0;
            }
        }
        if (curr == -1) {
            O(0);
        }
        else {
            int ans = curr;
            int last = n;
            while (curr != -1) {
                for (int i = last; i >= curr; i--) {
                    for (int x : pos[i]) {
                        st.erase(mp(x, i));
                    }
                }
                last = curr - 1;
                while (curr != -1) {
                    curr--;
                    ok = 1;
                    for (int x : pos[curr]) {
                        st.insert(mp(x, curr));
                        auto it = st.find(mp(x, curr));
                        if (it != st.begin()) {
                            it--;
                            if (it->second > curr) ok = 0;
                            it++;
                        }
                        it++;
                        if (it != st.end()) {
                            if (it->second < curr) ok = 0;
                        }
                        if (!ok) {
                            break;
                        }
                    }
                    if (!ok) {
                        for (int x : pos[curr]) {
                            st.erase(mp(x, curr));
                        }
                        curr++;
                        break;
                    }
                    else if (curr == 1) curr = -1;
                }
            }
            int temp = n - last;
            if (curr != -1) temp += curr;
            ans = min(ans, temp);
            O(ans);
        }
    }

    return 0;
}


#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;

#define     LL                      long long int
#define     LD                      long double
#define     ULL                     unsigned long long int

#define     pii                     pair<int, int>
#define     ump                     unordered_map
#define     mp                      make_pair
#define     mt                      make_tuple
#define     pb                      push_back
#define     ff                      first
#define     ss                      second
#define     SZ(x)                   (int)x.size()
#define     all(x)                  x.begin(), x.end()
#define     lb(x, y)                lower_bound(all(x), y)
#define     fill2d(arr, a, b, v)    fill(&arr[0][0], &arr[0][0] + a * b, v)
#define     fill3d(arr, a, b, c, v) fill(&arr[0][0], &arr[0][0] + a * b * c, v)
#define     rep(i, begin, end)      for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))

#define     sp(x)                   setprecision(x) << fixed
#define     what_is(x)              cout << #x << " is " << x << endl
//#define     I64                     ll

#define     PI                      acos(-1.0)
#define     EPS                     1e-12
#define     mx                      200010
#define     S_SIZE                  2000010

const LL inf = 1000000000;
const LL mod = 1000000000 + 7;

inline void IO() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); }
inline int dcmp (LD x) { return x < -EPS ? -1 : (x > EPS); }

template<class T> inline int CHECK(T MASK, int i) { return (MASK >> i) & 1; }
template<class T> inline T ON(T MASK, int i) { return MASK | (T(1) << i); }
template<class T> inline T OFF(T MASK, int i) { return MASK & (~(T(1) << i)); }
template<typename T> inline int CNT(T MASK) {
    if (numeric_limits<T>::digits <= numeric_limits<unsigned int>::digits) return __builtin_popcount(MASK);
    else return __builtin_popcountll(MASK);
}
template<class T> inline int RIGHT(T MASK) { return log2(MASK & -MASK); }

int dx4[] = { 0, 0, -1, +1 }; int dy4[] = { +1, -1, 0, 0 };
int dx8[] = { 1, 1, 0, -1, -1, -1, 0, 1, 0 }; int dy8[] = { 0, 1, 1, 1, 0, -1, -1, -1, 0 };

inline void I(int& a) { scanf("%d", &a); } inline void I(LL& a) { scanf("%I64d", &a); }
inline void I(ULL& a) { scanf("%I64u", &a); } inline void I(char* a) { scanf("%s", a); }
char Iarr[S_SIZE]; inline void I(string& a) { scanf("%s", Iarr); a = Iarr; }
template<typename T, typename... Args>
void I(T& a, Args&... args) { I(a); I(args...); }

inline void OUT(int a) { printf("%d", a); } inline void OUT(LL a) { printf("%I64d", a); }
inline void OUT(const char* a) { printf("%s", a); } inline void OUT(char* a) { printf("%s", a); }
inline void OUT(bool a) { printf("%d", a); } inline void OUT(string a) { rep(it, a.begin(), a.end()) printf("%c", *it); }
inline void OUT(ULL a) { printf("%I64u", a); }
template<typename T, typename... Args>
void OUT(T a, Args... args) { OUT(a); OUT(" "); OUT(args...); }
template<typename... Args>
void O(Args... args) { OUT(args...); OUT("\n"); }

template<typename T1, typename T2>
inline ostream& operator<<(ostream& os, pair<T1, T2> p) { os << "{" << p.first << ", " << p.second << "}"; return os; }
template<typename T>
inline ostream& operator<<(ostream& os, set<T>& a) { bool f = 0; os << "["; for (T i : a) { if (f) os << ", "; os << i; f = 1; } os << "]"; return os; }

#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
	cout << *it << " = " << a << endl;
	err(++it, args...);
}

// mp.reserve(1024); mp.max_load_factor(0.25);
// head

const int M = 300010; // maximum number of cubes

set<pii> st;
vector<int> pos[M];
int n;

void clr()
{
    st.clear();
    for (int i = 0; i <= n; i++) {
        pos[i].clear();
    }
}

int main()
{
    int q;
    I(q);
    while (q--) {
        clr();
        int nn;
        I(nn);
        int a[nn];
        set<int> stt;
        for (int i = 0; i < nn; i++) {
            I(a[i]);
            stt.insert(a[i]);
        }
        vector<int> vt;
        for (int x : stt) {
            vt.push_back(x);
        }
        for (int i = 0; i < nn; i++) {
            auto it = lower_bound(all(vt), a[i]);
            int p = it - vt.begin();
            p++;
            a[i] = p;
        }
        for (int i = 0; i < nn; i++) {
            pos[a[i]].pb(i);
        }
        n = SZ(vt);
        int curr = -1;
        bool ok = 1;
        for (int i = n; i >= 1; i--) {
            for (int x : pos[i]) {
                st.insert(mp(x, i));
                auto it = st.find(mp(x, i));
                if (it != st.begin()) {
                    it--;
                    if (it->second > i) ok = 0;
                    it++;
                }
                it++;
                if (it != st.end()) {
                    if (it->second < i) ok = 0;
                }
                if (!ok) {
                    curr = i;
                    break;
                }
            }
            if (!ok) {
                for (int x : pos[i]) {
                    st.erase(mp(x, i));
                }
                i = 0;
            }
        }
        if (curr == -1) {
            O(0);
        }
        else {
            int ans = curr;
            int last = n;
            int indx = 0;
            while (curr != -1) {
//                error(st, curr);
                for (int i = last; i >= last; i--) {
                    for (int x : pos[i]) {
                        st.erase(mp(x, i));
                    }
                }
                if (curr == last)
                    curr--;
                last--;
                if (curr == 0)
                    curr = -1;
//                error(st, curr);
                while (curr != -1) {
                    ok = 1;
                    for ( ; indx < SZ(pos[curr]); indx++) {
                        int x = pos[curr][indx];
                        st.insert(mp(x, curr));
                        auto it = st.find(mp(x, curr));
                        if (it != st.begin()) {
                            it--;
                            if (it->second > curr) ok = 0;
                            it++;
                        }
                        it++;
                        if (it != st.end()) {
                            if (it->second < curr) ok = 0;
                        }
                        if (!ok) {
                            break;
                        }
                    }
                    if (!ok) {
//                        error(curr);
                        int x = pos[curr][indx];
                        st.erase(mp(x, curr));
                        break;
                    }
                    else {
                        curr--;
                        indx = 0;
                        if (!curr)
                            curr = -1;
                    }
                }
//                error(st);
//                error(st, last, curr);
                int temp = n - last;
                if (curr != -1) temp += curr;
                ans = min(ans, temp);
            }
            O(ans);
        }
    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int q;
    cin >> q;
    while(q--){
        int n;
        cin >> n;
        vector<pair<int,int>> v(n);
        for(int i=0; i<n; i++){
            cin >> v[i].first;
            v[i].second=i;
        }
        sort(v.begin(),v.end());
        int x1=0;
        for(int i=0; i<n-1; i++){
            if(v[i].first!=v[i+1].first && v[i].second>v[i+1].second) x1++;
        }
        reverse(v.begin(),v.end());
        int x2=0;
        for(int i=0; i<n-1; i++){
            if(v[i].first!=v[i+1].first && v[i].second<v[i+1].second) x2++;
        }
        cout << min(x1,x2) << "\n";
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int q;
    cin >> q;
    while(q--){
        int n;
        cin >> n;
        vector<pair<int,int>> v(n);
        for(int i=0; i<n; i++){
            cin >> v[i].first;
            v[i].second=i;
        }
        sort(v.begin(),v.end());
        vector<int> p(n);
        p[n-1]=v[n-1].second;
        for(int i=n-2; i>=0; i--){
            p[i]=min(p[i+1],v[i].second);
        }
        int x1=0;
        for(int i=0; i<n-1; i++){
            if(v[i].first!=v[i+1].first && v[i].second>p[i+1]) x1++;
        }
        /*reverse(v.begin(),v.end());
        vector<int> s(n);
        s[0]=v[0].first;
        for(i=1; i<n; i++){
            s[i]=max(s[i-1],v[i].second);
        }
        int x2=0;
        for(int i=0; i<n-1; i++){
            if(v[i].first!=v[i+1].first && v[i].second<s[i+1]) x2++;
        }*/
        cout << x1 << "\n";
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int q;
    cin >> q;
    while(q--){
        int n;
        cin >> n;
        vector<pair<int,int>> v(n);
        for(int i=0; i<n; i++){
            cin >> v[i].first;
            v[i].second=i;
        }
        sort(v.begin(),v.end());
        int x=0;
        for(int i=0; i<n-1; i++){
            if(v[i].first!=v[i+1].first && v[i].second>v[i+1].second) x++;
        }
        cout << x << "\n";
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    int t;
    cin >> t;
    while(t--){
        int n;
        cin >> n;
        pair<int,int> p[n];
        for(int i=0; i<n; i++){
            cin >> p[i].first;
            p[i].second=i;
        }
        sort(p,p+n);
        int x=1,mx=1,unq=1;
        for(int i=0; i<n-1; i++){
            if(p[i].first!=p[i+1].first){
                unq++;
                if(p[i].second<p[i+1].second) x++;
                else x=1;
            }
            mx=max(x,mx);
        }
        cout << unq-mx << endl;
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int q;
    cin >> q;
    while(q--){
        int n;
        cin >> n;
        vector<pair<int,int>> v(n);
        for(int i=0; i<n; i++){
            cin >> v[i].first;
            v[i].second=i;
        }
        sort(v.begin(),v.end());
        vector<int> p(n);
        p[n-1]=v[n-1].second;
        for(int i=n-2; i>=0; i--){
            p[i]=min(p[i+1],v[i].second);
        }
        int x1=0;
        for(int i=0; i<n-1; i++){
            if(v[i].first!=v[i+1].first && v[i].second>p[i+1]) x1++;
        }
        reverse(v.begin(),v.end());
        vector<int> s(n);
        s[n-1]=v[n-1].second;
        for(int i=n-2; i>=0; i--){
            s[i]=max(s[i+1],v[i].second);
        }
        int x2=0;
        for(int i=0; i<n-1; i++){
            if(v[i].first!=v[i+1].first && v[i].second<s[i+1]) x2++;
        }
        cout << min(x1,x2) << "\n";
    }
    return 0;
}


    #include<bits/stdc++.h>
    using namespace std ;
    typedef long long ll ;
    const int maxn = 5e5 + 5 ;
    const int inf = 0x3f3f3f3f ;
    int q , n ;
    int l[maxn] ;
    int r[maxn] ;
    int ans ;
    int cnt ;
    int x , y ;
    struct Node
    {
    	int a , id ;
    	int b ;
    } node[maxn] ;
    bool cmp(Node xx , Node yy)
    {
    	if(xx.a != yy.a)
    	  return xx.a < yy.a ;
    	else
    	  return xx.id < yy.id ;
    }
    int main()
    {
    	scanf("%d" , &q) ;
    	while(q --)
    	{
    		scanf("%d" , &n) ;
    		for(int i = 1 ; i <= n ; i ++)
    		{
    		  scanf("%d" , &node[i].a) ;
    		  node[i].id = i ;
    		}
    		sort(node + 1 , node + n + 1 , cmp) ;
    		node[1].b = 1 ;
    		cnt = 1 ;
    		for(int i = 2 ; i <= n ; i ++)
    		{
    			if(node[i].a == node[i - 1].a)
    			  node[i].b = node[i - 1].b ;
    			else
    			{
    				cnt ++ ;
    				node[i].b = node[i - 1].b + 1 ;
    			}
    		}
    		for(int i = 1 ; i <= cnt ; i ++)
			{
			   l[i] = inf ;
			   r[i] = -1 ;
			}
    		for(int i = 1 ; i <= n ; i ++)
    		{
    			x = node[i].b ;
    			l[x] = min(l[x] , node[i].id) ;
    		    r[x] = max(r[x] , node[i].id) ;
    		}
    		ans = inf ;
    		for(int i = 1 ; i <= cnt ; i ++)
    		{
    			int j = i ;
    			while(j + 1 <= cnt && r[j] < l[j + 1])
    			  j ++ ;
    			ans = min(ans , cnt - (j - i + 1)) ;
    			i = j ;
    		}
    		printf("%d\n" , ans) ;
    	}
    }


#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
const int maxn = 5e5 + 5 ;
const int inf = 0x3f3f3f3f ;
int q , n ;
int l[maxn] ;
int r[maxn] ;
int ans ;
int cnt ;
int x , y ;
struct Node
{
	int a , id ;
	int b ;
} node[maxn] ;
bool cmp(Node xx , Node yy)
{
	if(xx.a != yy.a)
	  return xx.a < yy.a ;
	else
	  return xx.id < yy.id ;
}
int main()
{
	scanf("%d" , &q) ;
	while(q --)
	{
		scanf("%d" , &n) ;
		memset(l , inf , sizeof(l)) ;
		memset(r , -1 , sizeof(r)) ;
		for(int i = 1 ; i <= n ; i ++)
		{
		  scanf("%d" , &node[i].a) ;
		  node[i].id = i ;
		}
		sort(node + 1 , node + n + 1 , cmp) ;
		node[1].b = 1 ;
		cnt = 1 ;
		for(int i = 2 ; i <= n ; i ++)
		{
			if(node[i].a == node[i - 1].a)
			  node[i].b = node[i - 1].b ;
			else
			{
				cnt ++ ;
				node[i].b = node[i - 1].b + 1 ;
			}
		}
		for(int i = 1 ; i <= n ; i ++)
		{
			x = node[i].b ;
			l[x] = min(l[x] , node[i].id) ;
		    r[x] = max(r[x] , node[i].id) ;
		}
		ans = inf ;
		for(int i = 1 ; i <= cnt ; i ++)
		{
			int j = i ;
			while(j + 1 <= cnt && r[i] < l[j + 1])
			  j ++ ;
			ans = min(ans , cnt - (j - i + 1)) ;
		}
		printf("%d\n" , ans) ;
	}//
}


#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
const int maxn = 5e5 + 5 ;
const int inf = 0x3f3f3f3f ;
int q , n ;
int l[maxn] ;
int r[maxn] ;
int ans ;
int cnt ;
int x , y ;
struct Node
{
	int a , id ;
	int b ;
} node[maxn] ;
bool cmp(Node xx , Node yy)
{
	if(xx.a != yy.a)
	  return xx.a < yy.a ;
	else
	  return xx.id < yy.id ;
}
int main()
{
	scanf("%d" , &q) ;
	while(q --)
	{
		scanf("%d" , &n) ;
		memset(l , inf , sizeof(l)) ;
		memset(r , -1 , sizeof(r)) ;
		for(int i = 1 ; i <= n ; i ++)
		{
		  scanf("%d" , &node[i].a) ;
		  node[i].id = i ;
		}
		sort(node + 1 , node + n + 1 , cmp) ;
		node[1].b = 1 ;
		cnt = 1 ;
		for(int i = 2 ; i <= n ; i ++)
		{
			if(node[i].a == node[i - 1].a)
			  node[i].b = node[i - 1].b ;
			else
			{
				cnt ++ ;
				node[i].b = node[i - 1].b + 1 ;
			}
		}
		for(int i = 1 ; i <= n ; i ++)
		{
			x = node[i].b ;
			l[x] = min(l[x] , node[i].id) ;
		    r[x] = max(r[x] , node[i].id) ;
		}
		ans = inf ;
		for(int i = 1 ; i <= cnt ; i ++)
		{
			int j = i ;
			while(j + 1 <= cnt && r[i] < l[j + 1])
			  j ++ ;
			ans = min(ans , cnt - (j - i + 1)) ;
		}
		printf("%d\n" , ans) ;
	}
}


#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
const int maxn = 5e5 + 5 ;
const int inf = 0x3f3f3f3f ;
int q , n ;
int l[maxn] ;
int r[maxn] ;
bool used[maxn] ;
int id[maxn] ;
int ans ;
int cnt ;
int x , y ;
struct Node
{
	int a , id ;
	int b ;
} node[maxn] ;
bool cmp(Node xx , Node yy)
{
	if(xx.a != yy.a)
	  return xx.a < yy.a ;
	else
	  return xx.id < yy.id ;
}
int main()
{
	scanf("%d" , &q) ;
	while(q --)
	{
		scanf("%d" , &n) ;
		memset(l , inf , sizeof(l)) ;
		memset(r , -1 , sizeof(r)) ;
		memset(used , 0 , sizeof(used)) ;
		memset(id , -1 , sizeof(id)) ;
		for(int i = 1 ; i <= n ; i ++)
		{
		  scanf("%d" , &node[i].a) ;
		  node[i].id = i ;
		}
		sort(node + 1 , node + n + 1 , cmp) ;
		node[1].b = 1 ;
		cnt = 1 ;
		for(int i = 2 ; i <= n ; i ++)
		{
			if(node[i].a == node[i - 1].a)
			  node[i].b = node[i - 1].b ;
			else
			{
				cnt ++ ;
				node[i].b = node[i - 1].b + 1 ;
			}
		}
		for(int i = 1 ; i <= n ; i ++)
		{
			x = node[i].a ;
			y = node[i].b ;
			id[x] = y ;
			l[y] = min(l[y] , node[i].id) ;
		    r[y] = max(r[y] , node[i].id) ;
		}
		ans = inf ;
		for(int i = 1 ; i <= cnt ; i ++)
		{
			int j = i ;
			while(j + 1 <= cnt && r[i] < l[j + 1])
			  j ++ ;
			ans = min(ans , cnt - (j - i + 1)) ;
		}
		/*for(int i = 1 ; i <= n ; i ++)
		{
			x = node[i].b ;
			int j = i ;
			while(j + 1 <= n && node[j + 1].b >= node[i].b && node[j + 1].id > node[i].id)
			  j ++ ;
			y = node[j].b ;
			ans = min(ans , node[n].id - (y - x + 1)) ;
		}*/
		printf("%d\n" , ans) ;
	}
}


#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
const int maxn = 5e5 + 5 ;
const int inf = 0x3f3f3f3f ;
int q , n ;
int l[maxn] ;
int r[maxn] ;
int ans ;
int cnt ;
int x , y ;
struct Node
{
	int a , id ;
	int b ;
} node[maxn] ;
bool cmp(Node xx , Node yy)
{
	if(xx.a != yy.a)
	  return xx.a < yy.a ;
	else
	  return xx.id < yy.id ;
}
int main()
{
	scanf("%d" , &q) ;
	while(q --)
	{
		scanf("%d" , &n) ;
		memset(l , inf , sizeof(l)) ;
		memset(r , -1 , sizeof(r)) ;
		for(int i = 1 ; i <= n ; i ++)
		{
		  scanf("%d" , &node[i].a) ;
		  node[i].id = i ;
		}
		sort(node + 1 , node + n + 1 , cmp) ;
		node[1].b = 1 ;
		cnt = 1 ;
		for(int i = 2 ; i <= n ; i ++)
		{
			if(node[i].a == node[i - 1].a)
			  node[i].b = node[i - 1].b ;
			else
			{
				cnt ++ ;
				node[i].b = node[i - 1].b + 1 ;
			}
		}
		for(int i = 1 ; i <= n ; i ++)
		{
			x = node[i].b ;
			l[x] = min(l[x] , node[i].id) ;
		    r[x] = max(r[x] , node[i].id) ;
		}
		ans = inf ;
		for(int i = 1 ; i <= cnt ; i ++)
		{
			int j = i ;
			while(j + 1 <= cnt && r[i] < l[j + 1])
			  j ++ ;
			i = j ;
			ans = min(ans , cnt - (j - i + 1)) ;
		}
		printf("%d\n" , ans) ;
	}
}


    #include<bits/stdc++.h>
    using namespace std ;
    typedef long long ll ;
    const int maxn = 5e5 + 5 ;
    const int inf = 0x3f3f3f3f ;
    int q , n ;
    int l[maxn] ;
    int r[maxn] ;
    int ans ;
    int cnt ;
    int x , y ;
    struct Node
    {
    	int a , id ;
    	int b ;
    } node[maxn] ;
    bool cmp(Node xx , Node yy)
    {
    	if(xx.a != yy.a)
    	  return xx.a < yy.a ;
    	else
    	  return xx.id < yy.id ;
    }
    int main()
    {
    	scanf("%d" , &q) ;
    	while(q --)
    	{
    		scanf("%d" , &n) ;
    		memset(l , inf , sizeof(l)) ;
    		memset(r , -1 , sizeof(r)) ;
    		for(int i = 1 ; i <= n ; i ++)
    		{
    		  scanf("%d" , &node[i].a) ;
    		  node[i].id = i ;
    		}
    		sort(node + 1 , node + n + 1 , cmp) ;
    		node[1].b = 1 ;
    		cnt = 1 ;
    		for(int i = 2 ; i <= n ; i ++)
    		{
    			if(node[i].a == node[i - 1].a)
    			  node[i].b = node[i - 1].b ;
    			else
    			{
    				cnt ++ ;
    				node[i].b = node[i - 1].b + 1 ;
    			}
    		}
    		for(int i = 1 ; i <= n ; i ++)
    		{
    			x = node[i].b ;
    			l[x] = min(l[x] , node[i].id) ;
    		    r[x] = max(r[x] , node[i].id) ;
    		}
    		ans = inf ;
    		for(int i = 1 ; i <= cnt ; i ++)
    		{
    			int j = i ;
    			while(j + 1 <= cnt && r[i] < l[j + 1])
    			  j ++ ;
    			ans = min(ans , cnt - (j - i + 1)) ;
    			i = j ;
    		}
    		printf("%d\n" , ans) ;
    	}
    }


    #include<bits/stdc++.h>
    using namespace std ;
    typedef long long ll ;
    const int maxn = 5e5 + 5 ;
    const int inf = 0x3f3f3f3f ;
    int q , n ;
    int l[maxn] ;
    int r[maxn] ;
    int ans ;
    int cnt ;
    int x , y ;
    struct Node
    {
    	int a , id ;
    	int b ;
    } node[maxn] ;
    bool cmp(Node xx , Node yy)
    {
    	if(xx.a != yy.a)
    	  return xx.a < yy.a ;
    	else
    	  return xx.id < yy.id ;
    }
    int main()
    {
    	scanf("%d" , &q) ;
    	while(q --)
    	{
    		scanf("%d" , &n) ;
    		for(int i = 1 ; i <= n ; i ++)
    		{
    		  scanf("%d" , &node[i].a) ;
    		  node[i].id = i ;
    		}
    		sort(node + 1 , node + n + 1 , cmp) ;
    		node[1].b = 1 ;
    		cnt = 1 ;
    		for(int i = 2 ; i <= n ; i ++)
    		{
    			if(node[i].a == node[i - 1].a)
    			  node[i].b = node[i - 1].b ;
    			else
    			{
    				cnt ++ ;
    				node[i].b = node[i - 1].b + 1 ;
    			}
    		}
    		for(int i = 1 ; i <= cnt ; i ++)
			{
			   l[i] = inf ;
			   r[i] = -1 ;
			}
    		for(int i = 1 ; i <= n ; i ++)
    		{
    			x = node[i].b ;
    			l[x] = min(l[x] , node[i].id) ;
    		    r[x] = max(r[x] , node[i].id) ;
    		}
    		ans = inf ;
    		for(int i = 1 ; i <= cnt ; i ++)
    		{
    			int j = i ;
    			while(j + 1 <= cnt && r[i] < l[j + 1])
    			  j ++ ;
    			ans = min(ans , cnt - (j - i + 1)) ;
    			i = j ;
    		}
    		printf("%d\n" , ans) ;
    	}
    }


/**************************************************************************
Coded by: Saba Karimi(_VINTAGE)
Institution: AIT PUNE
***************************************************************************/
#include<bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define pb push_back
#define all(a) a.begin(),a.end()
#define lb lower_bound
#define ub upper_bound
#define pii pair<int,int>
#define ld long double
#define int long long int
#define F first
#define S second
/**************************************************************************/
signed main()
{
    fast;
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        int first[n+1],last[n+1];
        set<int> st;
        for(int i=1;i<=n;i++)
        {
            first[i] = 1e18;
            last[i] = -1;
        }
        int a[n+1];
        for(int i=1;i<=n;i++)
        {
            cin>>a[i];
            st.insert(a[i]);
            first[a[i]] = min(i,first[a[i]]);
            last[a[i]] = max(i,last[a[i]]);
        }
        int j = 0;
        for(auto it:st)
            a[j++] = it;
        n = st.size();
        int dp[n];
        dp[0] = 1;
        for(int i=1;i<n;i++)
        {
            dp[i] = 1;
            if(last[a[i-1]]<first[a[i]])
            {
                dp[i] = 1+dp[i-1];
            }
            else dp[i] = dp[i-1];
        }
       // cout<<dp[n]<<endl;
        cout<<n-dp[n-1]<<"\n";
    }
}


/**************************************************************************
Coded by: Saba Karimi(_VINTAGE)
Institution: AIT PUNE
***************************************************************************/
#include<bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define pb push_back
#define all(a) a.begin(),a.end()
#define lb lower_bound
#define ub upper_bound
#define pii pair<int,int>
#define ld long double
#define int long long int
#define F first
#define S second
/**************************************************************************/
signed main()
{
    fast;
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        int first[n+1],last[n+1];
        set<int> st;
        for(int i=1;i<=n;i++)
        {
            first[i] = 1e18;
            last[i] = -1;
        }
        int a[n+1];
        for(int i=1;i<=n;i++)
        {
            cin>>a[i];
            st.insert(a[i]);
            first[a[i]] = min(i,first[a[i]]);
            last[a[i]] = max(i,last[a[i]]);
        }
        int dp[n+1];
        dp[1] = 1;
        for(int i=2;i<=n;i++)
        {
            dp[i] = 1;
            for(int j=1;j<i;j++)
            {
                if(a[i]>a[j] && last[a[j]]<first[a[i]])
                    dp[i] = max(dp[i],1+dp[j]);
            }
        }
       // cout<<dp[n]<<endl;
        cout<<st.size()-dp[n]<<"\n";
    }
}


/**************************************************************************
Coded by: Saba Karimi(_VINTAGE)
Institution: AIT PUNE
***************************************************************************/
#include<bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define pb push_back
#define all(a) a.begin(),a.end()
#define lb lower_bound
#define ub upper_bound
#define pii pair<int,int>
#define ld long double
#define int long long int
#define F first
#define S second
/**************************************************************************/
signed main()
{
    fast;
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        int first[n+1],last[n+1];
        set<int> st;
        for(int i=1;i<=n;i++)
        {
            first[i] = 1e18;
            last[i] = -1;
        }
        int a[n+1];
        for(int i=1;i<=n;i++)
        {
            cin>>a[i];
            st.insert(a[i]);
            first[a[i]] = min(i,first[a[i]]);
            last[a[i]] = max(i,last[a[i]]);
        }
        int j = 0;
        for(auto it:st)
            a[j++] = it;
        n = st.size();
        int dp[n];
        dp[0] = 1;
        for(int i=1;i<n;i++)
        {
            if(last[a[i-1]]<first[a[i]])
            {
                dp[i] = 1+dp[i-1];
            }
            else dp[i] = 1;
        }
        for(int i=1;i<n;i++)
            dp[i] = max(dp[i],dp[i-1]);
        cout<<n-dp[n-1]<<"\n";
    }
}


/**************************************************************************
Coded by: Saba Karimi(_VINTAGE)
Institution: AIT PUNE
***************************************************************************/
#include<bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define pb push_back
#define all(a) a.begin(),a.end()
#define lb lower_bound
#define ub upper_bound
#define pii pair<int,int>
#define ld long double
#define int long long int
#define F first
#define S second
/**************************************************************************/
signed main()
{
    fast;
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        int first[n+1],last[n+1];
        set<int> st;
        for(int i=1;i<=n;i++)
        {
            first[i] = 1e18;
            last[i] = -1;
        }
        int a[n+1];
        for(int i=1;i<=n;i++)
        {
            cin>>a[i];
            st.insert(a[i]);
            first[a[i]] = min(i,first[a[i]]);
            last[a[i]] = max(i,last[a[i]]);
        }
        int j = 0;
        for(auto it:st)
            a[j++] = it;
        n = st.size();
        int dp[n];
        dp[0] = 1;
        for(int i=1;i<n;i++)
        {
            dp[i] = 1;
            for(int j=0;j<i;j++)
            {
                if(a[i]>a[j] && last[a[j]]<first[a[i]])
                    dp[i] = max(dp[i],1+dp[j]);
            }
        }
       // cout<<dp[n]<<endl;
        cout<<n-dp[n-1]<<"\n";
    }
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=3e5+100;
const ll mod=1e9+7;
int n,m,k,t;
struct ac{
    int x,y;
}a[maxn];
int l[maxn],r[maxn];
int main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(int i=1;i<=n;i++)l[i]=0;
        for(int i=1;i<=n;i++){
            scanf("%d",&k);
            if(!l[k])
                l[k]=i;
            r[k]=i;
        }
        int z=0;
        for(int i=1;i<=n;i++){
            if(l[i]){
                a[++z].x=l[i];
                a[z].y=r[i];
            }
        }
        int maxm=1,now=1;
        for(int i=2;i<=z;i++){
            if(a[i].x>a[i-1].y)
                now++,maxm=max(now,maxm);
            else
                now=1;
        }
        printf("%d\n",z-maxm);
    }
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=2e5+100;
const ll mod=1e9+7;
int n,m,k,t;
struct ac{
    int x,y;
}a[maxn];
int l[maxn],r[maxn];
int main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(int i=1;i<=n;i++){
            l[i]=0;
            scanf("%d",&k);
            if(!l[k])
                l[k]=i;
            r[k]=i;
        }
        int z=0;
        for(int i=1;i<=n;i++){
            if(l[i]){
                a[++z].x=l[i];
                a[z].y=r[i];
            }
        }
        int maxm=1,now=1;
        for(int i=2;i<=z;i++){
            if(a[i].x>a[i-1].y)
                now++,maxm=max(now,maxm);
            else
                now=1;
        }
        printf("%d\n",z-maxm);
    }
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=2e5+100;
const ll mod=1e9+7;
int n,m,k,t;
struct ac{
    int x,y;
}a[maxn];
int l[maxn],r[maxn];
int main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(int i=1;i<=n;i++)l[i]=0;
        for(int i=1;i<=n;i++){
            scanf("%d",&k);
            if(!l[k])
                l[k]=i;
            r[k]=i;
        }
        int z=0;
        for(int i=1;i<=n;i++){
            if(l[i]){
                a[++z].x=l[i];
                a[z].y=r[i];
            }
        }
        int maxm=1,now=1;
        for(int i=2;i<=z;i++){
            if(a[i].x>a[i-1].y)
                now++,maxm=max(now,maxm);
            else
                now=1;
        }
        printf("%d\n",z-maxm);
    }
}


/*suri_kumkaran*/

#include <bits/stdc++.h>

using namespace std;

#define UB upper_bound
#define LB lower_bound
#define BS binary_search
#define MP make_pair
#define EB emplace_back
#define endl "\n"
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
#define F first
#define S second
#define ALL(a) (a).begin(),(a).end()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)

typedef long long int int64;
typedef vector<int64> VI64;
typedef vector<pair<int64,int64>> VII64;
typedef vector<string> VS;
typedef vector<vector<int64>> VVI;

int main()
{
    IOS;
    int64 T=1;
    cin>>T;
    while(T--)
    {
        int64 n,i,tem;
        cin>>n;
        unordered_map<int,int> lst;
        map<int,int> fst;
        for(i=0;i<n;i++)
        {
            cin>>tem;
            if(fst.find(tem)==fst.end())
                fst[tem]=i;
            lst[tem]=i;
        }
        VI64 v;
        for(auto x:fst)
        {
            v.EB(x.F);
        }
        int64 mx=1;
        int64 dp[v.size()];
        dp[0]=1;

        for(i=1;i<v.size();i++)
        {
            if(lst[v[i-1]]>fst[v[i]])
            {
                dp[i]=1;
            }
            else
                dp[i]=dp[i-1]+1;
            mx=max(mx,dp[i]);
        }

        cout<<v.size()-mx<<endl;

    }

    return 0;
}


/*suri_kumkaran*/

#include <bits/stdc++.h>

using namespace std;

#define UB upper_bound
#define LB lower_bound
#define BS binary_search
#define MP make_pair
#define EB emplace_back
#define endl "\n"
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
#define F first
#define S second
#define ALL(a) (a).begin(),(a).end()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)

typedef long long int int64;
typedef vector<int64> VI64;
typedef vector<pair<int64,int64>> VII64;
typedef vector<string> VS;
typedef vector<vector<int64>> VVI;

int64 n;

void update(int64 idx,int64 *BIT)
{
  while(idx<=n)
  {
    BIT[idx]++;
    idx+=((idx)&(-idx));
  }
}

int64 query(int64 idx,int64 *BIT)
{
  int64 ans=0;
  while(idx>0)
  {
    ans+=BIT[idx];
    idx-=((idx)&(-idx));
  }
  return ans;
}

int main()
{
	IOS;
	int64 T=1;
	cin>>T;
	while(T--)
	{
		int64 i,j;
		cin>>n;
		unordered_map<int64,int64> mp;
		int64 BIT[n+1]={0};
		int64 a[n];
		int64 str=n-n/2;
		for(i=0;i<n;i++)
		{
			cin>>a[i];
		}
		for(i=n-1;i>=0;i--)
		{
			if(a[i]>str)
			{
				int64 cnt=query(a[i]-1,BIT)-query(n-a[i]+1,BIT);
				if(cnt)
					mp[a[i]]++;
			}
			update(a[i],BIT);
		}
		int64 BIT2[n+1]={0};
		for(i=0;i<n;i++)
		{
			if(a[i]<=str)
			{
				int64 cnt=query(n+1-a[i],BIT2)-query(a[i],BIT2);
				if(cnt)
					mp[a[i]]++;
			}
			update(a[i],BIT2);
		}
		cout<<mp.size()<<endl;

	}

	return 0;
}


/*suri_kumkaran*/

#include <bits/stdc++.h>

using namespace std;

#define UB upper_bound
#define LB lower_bound
#define BS binary_search
#define MP make_pair
#define EB emplace_back
#define endl "\n"
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
#define F first
#define S second
#define ALL(a) (a).begin(),(a).end()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)

typedef long long int int64;
typedef vector<int64> VI64;
typedef vector<pair<int64,int64>> VII64;
typedef vector<string> VS;
typedef vector<vector<int64>> VVI;

int main()
{
	IOS;
	int64 T=1;
	cin>>T;
	while(T--)
	{
		int64 n,i;
		cin>>n;
		unordered_map<int64,int64> mp;
		int64 mx=0;
		int64 a[n];
		for(i=0;i<n;i++)
		{
			cin>>a[i];
			if(a[i]<mx)
				mp[a[i]]++;
			mx=max(mx,a[i]);
		}
		cout<<mp.size()<<endl;
	}

	return 0;
}


/*suri_kumkaran*/

#include <bits/stdc++.h>

using namespace std;

#define UB upper_bound
#define LB lower_bound
#define BS binary_search
#define MP make_pair
#define EB emplace_back
#define endl "\n"
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
#define F first
#define S second
#define ALL(a) (a).begin(),(a).end()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)

typedef long long int int64;
typedef vector<int64> VI64;
typedef vector<pair<int64,int64>> VII64;
typedef vector<string> VS;
typedef vector<vector<int64>> VVI;

int64 n;

void update(int64 idx,int64 *BIT)
{
  while(idx<=n)
  {
    BIT[idx]++;
    idx+=((idx)&(-idx));
  }
}

int64 query(int64 idx,int64 *BIT)
{
  int64 ans=0;
  while(idx>0)
  {
    ans+=BIT[idx];
    idx-=((idx)&(-idx));
  }
  return ans;
}

int main()
{
	IOS;
	int64 T=1;
	cin>>T;
	while(T--)
	{
		int64 i,j;
		cin>>n;
		unordered_map<int64,int64> mp;
		int64 BIT[n+1]={0};
		int64 a[n];
		int64 str=n-n/2;
		for(i=0;i<n;i++)
		{
			cin>>a[i];
		}
		for(i=n-1;i>=0;i--)
		{
			if(a[i]>str)
			{
				int64 mx=max(a[i]-1,n-a[i]+1);
				int64 mn=min(a[i]-1,n-a[i]+1);
				//cout<<a[i]<<" "<<mx<<" "<<mn<<endl;
				int64 cnt=query(mx,BIT)-query(mn,BIT);
				if(cnt)
				{
					/*cout<<a[i]-1<<" "<<n-a[i]+1<<endl;
					cout<<cnt<<endl;*/
					mp[a[i]]++;
				}
			}
			update(a[i],BIT);
			//cout<<query(1,BIT)<<" "<<query(n,BIT)<<endl;
		}
		int64 BIT2[n+1]={0};
		for(i=0;i<n;i++)
		{
			if(a[i]<=str)
			{
				int64 mx=max(n+1-a[i],a[i]);
				int64 mn=min(n+1-a[i],a[i]);
				//cout<<a[i]<<" "<<mx<<" "<<mn<<endl;
				int64 cnt=query(mx,BIT2)-query(mn,BIT2);
				//cout<<cnt<<endl;
				if(cnt)
					mp[a[i]]++;
			}
			update(a[i],BIT2);
		}
		cout<<mp.size()<<endl;

	}

	return 0;
}


/*suri_kumkaran*/

#include <bits/stdc++.h>

using namespace std;

#define UB upper_bound
#define LB lower_bound
#define BS binary_search
#define MP make_pair
#define EB emplace_back
#define endl "\n"
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
#define F first
#define S second
#define ALL(a) (a).begin(),(a).end()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)

typedef long long int int64;
typedef vector<int64> VI64;
typedef vector<pair<int64,int64>> VII64;
typedef vector<string> VS;
typedef vector<vector<int64>> VVI;

int main()
{
    IOS;
    int64 T=1;
    cin>>T;
    while(T--)
    {
        int64 n,i,tem;
        cin>>n;
        map<int,int> lst,fst;
        for(i=0;i<n;i++)
        {
            cin>>tem;
            if(fst.find(tem)==fst.end())
                fst[tem]=i;
            lst[tem]=i;
        }
        VI64 v;
        for(auto x:fst)
        {
            v.EB(x.F);
        }
        int64 mx=1;
        int64 dp[v.size()];
        dp[0]=1;

        for(i=1;i<v.size();i++)
        {
            if(lst[v[i-1]]>fst[v[i]])
            {
                dp[i]=1;
            }
            else
                dp[i]=dp[i-1]+1;
            mx=max(mx,dp[i]);
        }

        cout<<v.size()-mx<<endl;

    }

    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits.h>
#include <map>
#include <unordered_map>
#include <cmath>
#include <set>
#include <iterator>
#include <deque>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
ull min(ull x, ull y){ if (x<y) return x; return y;}
ull max(ull x, ull y){ if (x<y) return y; return x;}
ll min(ll x, ll y){ if (x<y) return x; return y;}
ll max(ll x, ll y){ if (x<y) return y; return x;}
ull gcd(ull x, ull y){
    if (!x) return y;
    if (!y) return x;
    if (x>y) swap(x,y);
    return gcd(x, y%x);
}

int main(){

    int q;
    cin>>q;
    while (q--){
        int n;
        cin>>n;
        int l[300003] = {0}, r[300003] = {0}, a[300003] = {0}, mine = INT_MAX, maxe = 0;
        vector<int> uniq;
        for (int i = 1; i <= n; i++){
            cin>>a[i];
            if (!l[a[i]]){
                l[a[i]] = i;
            }
            mine = min(mine, a[i]);
            maxe = max(maxe, a[i]);
        }
        for (int i = n; i > 0; i--){
            if (!r[a[i]]) r[a[i]] = i;
        }
        for (int i = 1; i <= n; i++){
            if (l[i]) uniq.push_back(i);
        }

        int dp[300003][2] = {0};
        for (int i = 1; i < uniq.size(); i++){
            int cur = uniq[i], prev = uniq[i-1];
            if (r[prev] < l[cur]){
                dp[cur][0] = dp[prev][0];
            }
            else{
                dp[cur][0] = i;
            }
            dp[cur][1] = min(dp[prev][0],dp[prev][1]) + 1;
        }

        cout<<min(dp[maxe][0],dp[maxe][1])<<"\n";
    }

    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits.h>
#include <map>
#include <unordered_map>
#include <cmath>
#include <set>
#include <iterator>
#include <deque>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
ull min(ull x, ull y){ if (x<y) return x; return y;}
ull max(ull x, ull y){ if (x<y) return y; return x;}
ll min(ll x, ll y){ if (x<y) return x; return y;}
ll max(ll x, ll y){ if (x<y) return y; return x;}
ull gcd(ull x, ull y){
    if (!x) return y;
    if (!y) return x;
    if (x>y) swap(x,y);
    return gcd(x, y%x);
}

int main(){

    int q;
    cin>>q;
    while (q--){
        int n;
        cin>>n;
        int l[300003] = {0}, r[300003] = {0}, a[300003] = {0}, mine = INT_MAX, maxe = 0;
        vector<int> uniq;
        for (int i = 1; i <= n; i++){
            cin>>a[i];
            if (!l[a[i]]){
                l[a[i]] = i;
                uniq.push_back(a[i]);
            }
            mine = min(mine, a[i]);
            maxe = max(maxe, a[i]);
        }
        for (int i = n; i > 0; i--){
            if (!r[a[i]]) r[a[i]] = i;
        }

        sort(uniq.begin(), uniq.end());

        int dp[300003][2] = {0};
        for (int i = 1; i < uniq.size(); i++){
            int cur = uniq[i], prev = uniq[i-1];
            if (r[prev] < l[cur]){
                dp[cur][0] = dp[prev][0];
            }
            else{
                dp[cur][0] = i;
            }
            dp[cur][1] = min(dp[prev][0],dp[prev][1]) + 1;
        }

        cout<<min(dp[maxe][0],dp[maxe][1])<<"\n";
    }

    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits.h>
#include <map>
#include <unordered_map>
#include <cmath>
#include <set>
#include <iterator>
#include <deque>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
ull min(ull x, ull y){ if (x<y) return x; return y;}
ull max(ull x, ull y){ if (x<y) return y; return x;}
ll min(ll x, ll y){ if (x<y) return x; return y;}
ll max(ll x, ll y){ if (x<y) return y; return x;}
ull gcd(ull x, ull y){
    if (!x) return y;
    if (!y) return x;
    if (x>y) swap(x,y);
    return gcd(x, y%x);
}

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int q;
    cin>>q;
    while (q--){
        int n;
        cin>>n;
        int l[n+1], r[n+1], a[n+1], maxe = 0, dp[n+1][2];
        for (int i = 0; i <= n; i++){
            l[i] = 0;
            r[i] = 0;
            a[i] = 0;
            dp[i][0] = 0;
            dp[i][1] = 0;
        }
        vector<int> uniq;
        for (int i = 1; i <= n; i++){
            cin>>a[i];
            if (!l[a[i]]){
                l[a[i]] = i;
            }
            r[a[i]] = i;
            maxe = max(maxe, a[i]);
        }
        for (int i = 1; i <= n; i++){
            if (l[i]) uniq.push_back(i);
        }

        for (int i = 1; i < uniq.size(); i++){
            int cur = uniq[i], prev = uniq[i-1];
            dp[cur][0] = i;
            if (r[prev] < l[cur]){
                dp[cur][0] = min(dp[prev][0],dp[cur][0]);
            }
            dp[cur][1] = min(dp[prev][0],dp[prev][1]) + 1;
        }

        cout<<min(dp[maxe][0],dp[maxe][1])<<"\n";
    }

    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits.h>
#include <map>
#include <unordered_map>
#include <cmath>
#include <set>
#include <iterator>
#include <deque>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
ull min(ull x, ull y){ if (x<y) return x; return y;}
ull max(ull x, ull y){ if (x<y) return y; return x;}
ll min(ll x, ll y){ if (x<y) return x; return y;}
ll max(ll x, ll y){ if (x<y) return y; return x;}
ull gcd(ull x, ull y){
    if (!x) return y;
    if (!y) return x;
    if (x>y) swap(x,y);
    return gcd(x, y%x);
}

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int q;
    cin>>q;
    while (q--){
        int n;
        cin>>n;
        int l[300003] = {0}, r[300003] = {0}, a[300003] = {0}, maxe = 0;
        vector<int> uniq;
        for (int i = 1; i <= n; i++){
            cin>>a[i];
            if (!l[a[i]]){
                l[a[i]] = i;
            }
            r[a[i]] = i;
            maxe = max(maxe, a[i]);
        }
        for (int i = 1; i <= n; i++){
            if (l[i]) uniq.push_back(i);
        }

        int dp[300003][2] = {0};
        for (int i = 1; i < uniq.size(); i++){
            int cur = uniq[i], prev = uniq[i-1];
            dp[cur][0] = i;
            if (r[prev] < l[cur]){
                dp[cur][0] = min(dp[prev][0],dp[cur][0]);
            }
            dp[cur][1] = min(dp[prev][0],dp[prev][1]) + 1;
        }

        cout<<min(dp[maxe][0],dp[maxe][1])<<"\n";
    }

    return 0;
}


#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int INF = 0x3c3c3c3c;
const ll INF_L = 0x3c3c3c3c3c3c3c3c;
const int MAX_N = 3e5 + 9;

int q;
int n;
int a[MAX_N], b[MAX_N], convert[MAX_N];
int leftIdx[MAX_N], rightIdx[MAX_N];
int cnt[MAX_N];
bool used[MAX_N];
map<pair<int, int>, bool> orders;

void solve(){
    cin >> n;
    memset(used, 0, sizeof(bool) * (n + 1));
    memset(cnt, 0, sizeof(int) * (n + 1));
    orders.clear();

    for(int i = 1; i <= n; i++){
        cin >> a[i];
    }

    for(int i = 1; i <= n; i++){
        b[i] = a[i];
    }
    sort(b + 1, b + 1 + n);

    int numbering = 1;
    for(int i = 1; i <= n; i++){
        int v = b[i];
        if(used[v]) continue;
        convert[v] = numbering;
        numbering++;
        used[v] = true;
    }
    numbering--;

    for(int i = 1; i <= n; i++){
        int v = a[i];
        a[i] = convert[v];
    }

    for(int i = 1; i <= n; i++){
        int v = a[i];
        cnt[v]++;
    }

    for(int i = 1; i <= n; i++){
        leftIdx[i] = INF;
        rightIdx[i] = 0;
    }

    for(int i = 1; i <= n; i++){
        int v = a[i];
        leftIdx[v] = min(leftIdx[v], i);
        rightIdx[v] = max(rightIdx[v], i);
    }

    int curr = 1;
    while(curr <= numbering){
        int cnt = 1;
        while(curr + cnt <= numbering && rightIdx[curr + cnt - 1] < leftIdx[curr + cnt]){
            cnt++;
        }
        orders[{curr, curr + cnt - 1}] = true;
        curr += cnt;
    }

    int ans = INF;
    for(auto &order : orders){
        auto &key = order.first;
        int l = key.first;
        int r = key.second;

        int sum = 0;
        if(l - 1 >= 1){
            sum += (l - 1) - (rightIdx[l - 1] == cnt[l - 1]);
        }
        if(r + 1 <= numbering){
            sum += (numbering - r) - (leftIdx[r + 1] == numbering - cnt[r + 1] + 1);
        }
        ans = min(ans, sum);
    }

    printf("%d\n", ans);
}

int main(){
    cin.sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int q;
    cin >> q;

    for(int i = 0; i < q; i++){
        solve();
    }
}


#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int INF = 0x3c3c3c3c;
const ll INF_L = 0x3c3c3c3c3c3c3c3c;

void solve(){
    int n;
    cin >> n;
    vector<int> a(n + 1, 0);
    vector<int> b(n + 1, 0);
    vector<int> convert(n + 1, 0);
    vector<int> leftIdx(n + 1, 0), rightIdx(n + 1, 0);
    vector<int> cnt(n + 1, 0);
    vector<bool> used(n + 1, false);

    for(int i = 1; i <= n; i++){
        cin >> a[i];
    }

    for(int i = 1; i <= n; i++){
        b[i] = a[i];
    }
    sort(b.begin() + 1, b.end());

    int numbering = 0;
    for(int i = 1; i <= n; i++){
        int v = b[i];
        if(used[v]) continue;
        numbering++;
        convert[v] = numbering;
        used[v] = true;
    }

    for(int i = 1; i <= n; i++){
        int v = a[i];
        a[i] = convert[v];
    }

    for(int i = 1; i <= n; i++){
        int v = a[i];
        cnt[v]++;
    }

    for(int i = 1; i <= n; i++){
        leftIdx[i] = INF;
        rightIdx[i] = 0;
    }

    for(int i = 1; i <= n; i++){
        int v = a[i];
        leftIdx[v] = min(leftIdx[v], i);
        rightIdx[v] = max(rightIdx[v], i);
    }

    int ans = INF;
    int curr = 1;
    while(curr <= numbering){
        int cnt = 1;
        while(curr + cnt <= numbering && rightIdx[curr + cnt - 1] < leftIdx[curr + cnt]){
            cnt++;
        }
        ans = min(ans, numbering - cnt);
        curr += cnt;
    }

    printf("%d\n", ans);
}

int main(){
    cin.sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int q;
    cin >> q;

    for(int i = 0; i < q; i++){
        solve();
    }
}


#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int INF = 0x3c3c3c3c;
const ll INF_L = 0x3c3c3c3c3c3c3c3c;
const int MAX_N = 3e5 + 9;

int q;
int n;
int a[MAX_N], b[MAX_N], convert[MAX_N];
int leftIdx[MAX_N], rightIdx[MAX_N];
int cnt[MAX_N];
bool used[MAX_N];
map<pair<int, int>, bool> orders;

void solve(){
    cin >> n;
    memset(used, 0, sizeof(bool) * (n + 1));
    memset(cnt, 0, sizeof(bool) * (n + 1));
    orders.clear();

    for(int i = 1; i <= n; i++){
        cin >> a[i];
    }

    for(int i = 1; i <= n; i++){
        b[i] = a[i];
    }
    sort(b + 1, b + 1 + n);

    int numbering = 1;
    for(int i = 1; i <= n; i++){
        int v = b[i];
        if(used[v]) continue;
        convert[v] = numbering;
        numbering++;
        used[v] = true;
    }
    numbering--;

    for(int i = 1; i <= n; i++){
        int v = a[i];
        a[i] = convert[v];
    }

    for(int i = 1; i <= n; i++){
        int v = a[i];
        cnt[v]++;
    }

    for(int i = 1; i <= n; i++){
        leftIdx[i] = INF;
        rightIdx[i] = 0;
    }

    for(int i = 1; i <= n; i++){
        int v = a[i];
        leftIdx[v] = min(leftIdx[v], i);
        rightIdx[v] = max(rightIdx[v], i);
    }

    int curr = 1;
    while(curr <= numbering){
        int cnt = 1;
        while(curr + cnt <= numbering && rightIdx[curr + cnt - 1] < leftIdx[curr + cnt]){
            cnt++;
        }
        orders[{curr, curr + cnt - 1}] = true;
        curr += cnt;
    }

    int ans = INF;
    for(auto &order : orders){
        auto &key = order.first;
        int l = key.first;
        int r = key.second;

        int sum = 0;
        if(l - 1 >= 1){
            sum += (l - 1) - (rightIdx[l - 1] == cnt[l - 1]);
        }
        if(r + 1 <= numbering){
            sum += (numbering - r) - (leftIdx[r + 1] == numbering - cnt[r + 1] + 1);
        }
        ans = min(ans, sum);
    }

    printf("%d\n", ans);
}

int main(){
    cin.sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int q;
    cin >> q;

    for(int i = 0; i < q; i++){
        solve();
    }
}


#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int INF = 0x3c3c3c3c;
const ll INF_L = 0x3c3c3c3c3c3c3c3c;
const int MAX_N = 3e5 + 9;

int q;
int n;
int a[MAX_N], b[MAX_N], convert[MAX_N];
int leftIdx[MAX_N], rightIdx[MAX_N];
int cnt[MAX_N];
bool used[MAX_N];
map<pair<int, int>, bool> orders;

void solve(){
    cin >> n;
    memset(used, 0, sizeof(bool) * (n + 1));
    memset(cnt, 0, sizeof(int) * (n + 1));
    orders.clear();

    for(int i = 1; i <= n; i++){
        cin >> a[i];
    }

    for(int i = 1; i <= n; i++){
        b[i] = a[i];
    }
    sort(b + 1, b + 1 + n);

    int numbering = 1;
    for(int i = 1; i <= n; i++){
        int v = b[i];
        if(used[v]) continue;
        convert[v] = numbering;
        numbering++;
        used[v] = true;
    }
    numbering--;

    for(int i = 1; i <= n; i++){
        int v = a[i];
        a[i] = convert[v];
    }

    for(int i = 1; i <= n; i++){
        int v = a[i];
        cnt[v]++;
    }

    for(int i = 1; i <= n; i++){
        leftIdx[i] = INF;
        rightIdx[i] = 0;
    }

    for(int i = 1; i <= n; i++){
        int v = a[i];
        leftIdx[v] = min(leftIdx[v], i);
        rightIdx[v] = max(rightIdx[v], i);
    }

    int curr = 1;
    while(curr <= numbering){
        int cnt = 1;
        while(curr + cnt <= numbering && rightIdx[curr + cnt - 1] < leftIdx[curr + cnt]){
            cnt++;
        }
        orders[{curr, curr + cnt - 1}] = true;
        curr += cnt;
    }

    int ans = INF;
    for(auto &order : orders){
        auto &key = order.first;
        int l = key.first;
        int r = key.second;

        int sum = 0;
        if(l - 1 >= 1){
            sum += (l - 1) - (rightIdx[l - 1] == cnt[l - 1]);
        }
        if(r + 1 <= numbering){
            sum += (n - r) - (leftIdx[r + 1] == n - cnt[r + 1] + 1);
        }
        ans = min(ans, sum);
    }

    printf("%d\n", ans);
}

int main(){
    cin.sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int q;
    cin >> q;

    for(int i = 0; i < q; i++){
        solve();
    }
}


/*   Author : Rshs
 *   Data : 2019-10-07-00.17
 */
#include<bits/stdc++.h>
using namespace std;
#define FI first
#define SE second
#define LL long long
#define MP make_pair
#define PII pair<int,int>
#define SZ(a) (int)a.size()
const double pai = acos(-1);
const double eps = 1e-10;
const LL mod = 1e9+7;
const int MXN = 1e6+5;
int maxpos[MXN];
int bigger[MXN];
int a[MXN];
vector<int>ls;
void Main(int avg){
    int n;cin>>n;
    ls.clear();
    for(int i=1;i<=n;i++) maxpos[i]=bigger[i]=0;
    for(int i=1;i<=n;i++) scanf("%d",&a[i]),ls.push_back(a[i]);
    sort(ls.begin(),ls.end());
    ls.erase(unique(ls.begin(),ls.end()),ls.end());
    for(int i=1;i<=n;i++){
        int id=lower_bound(ls.begin(),ls.end(),a[i])-ls.begin()+1;
        maxpos[id]= i;
    }
    int sz=SZ(ls);
    for(int i=2;i<=sz;i++){
        if(maxpos[i]>maxpos[i-1]) bigger[i]=1;
    }
    int mx=1,now=1;
    for(int i=2;i<=sz;i++){
        if(bigger[i]) now++;
        else mx=max(now,mx),now=1;
    }
    mx=max(now,mx);
    cout<<sz-mx<<'\n';
}
int main(){
    int cas;cin>>cas;for(int i=1;i<=cas;i++)Main(i);
    return 0;
}


/*   Author : Rshs
 *   Data : 2019-10-07-00.17
 */
#include<bits/stdc++.h>
using namespace std;
#define FI first
#define SE second
#define LL long long
#define MP make_pair
#define PII pair<int,int>
#define SZ(a) (int)a.size()
const double pai = acos(-1);
const double eps = 1e-10;
const LL mod = 1e9+7;
const int MXN = 1e6+5;
int maxpos[MXN];
int bigger[MXN];
int a[MXN];
vector<int>ls;
void Main(int avg){
    int n;cin>>n;
    ls.clear();
    for(int i=1;i<=n;i++) maxpos[i]=bigger[i]=0;
    for(int i=1;i<=n;i++) scanf("%d",&a[i]),ls.push_back(a[i]);
    sort(ls.begin(),ls.end());
    ls.erase(unique(ls.begin(),ls.end()),ls.end());
    for(int i=1;i<=n;i++){
        int id=lower_bound(ls.begin(),ls.end(),a[i])-ls.begin()+1;
        maxpos[id]= i;
    }
    int sz=SZ(ls);
    for(int i=2;i<=sz;i++){
        if(maxpos[i]>maxpos[i-1]) bigger[i]=1;
    }
    int mx=1,now=1;
    for(int i=2;i<=sz;i++){
        if(bigger[i]) now++;
        else mx=max(now,mx),now=1;
    }
    mx=max(now,mx);
    cout<<sz-mx <<'\n';
}
int main(){
    int cas;cin>>cas;for(int i=1;i<=cas;i++)Main(i);
    return 0;
}


/*   Author : Rshs
 *   Data : 2019-10-07-00.17
 */
#include<bits/stdc++.h>
using namespace std;
#define FI first
#define SE second
#define LL long long
#define MP make_pair
#define PII pair<int,int>
#define SZ(a) (int)a.size()
const double pai = acos(-1);
const double eps = 1e-10;
const LL mod = 1e9+7;
const int MXN = 1e6+5;
int maxpos[MXN],mi[MXN];
int bigger[MXN];
int a[MXN];
vector<int>ls;
void Main(int avg){
    int n;cin>>n;
    ls.clear();
    for(int i=1;i<=n;i++) maxpos[i]=bigger[i]=0;
    for(int i=1;i<=n;i++) scanf("%d",&a[i]),ls.push_back(a[i]);
    sort(ls.begin(),ls.end());
    ls.erase(unique(ls.begin(),ls.end()),ls.end());
    for(int i=1;i<=n;i++){
        int id=lower_bound(ls.begin(),ls.end(),a[i])-ls.begin()+1;
        maxpos[id]= i;
    }
    for(int i=n;i>=1;i--){
        int id=lower_bound(ls.begin(),ls.end(),a[i])-ls.begin()+1;
        mi[id]= i;
    }
    int sz=SZ(ls);
    for(int i=2;i<=sz;i++){
        if(mi[i]>maxpos[i-1]) bigger[i]=1;
    }
    int mx=1,now=1;
    for(int i=2;i<=sz;i++){
        if(bigger[i]) now++;
        else mx=max(now,mx),now=1;
    }
    mx=max(now,mx);
    cout<<sz-mx<<'\n';
}
int main(){
    int cas;cin>>cas;for(int i=1;i<=cas;i++)Main(i);
    return 0;
}


/*   Author : Rshs
 *   Data : 2019-10-07-00.17
 */
#include<bits/stdc++.h>
using namespace std;
#define FI first
#define SE second
#define LL long long
#define MP make_pair
#define PII pair<int,int>
#define SZ(a) (int)a.size()
const double pai = acos(-1);
const double eps = 1e-10;
const LL mod = 1e9+7;
const int MXN = 1e6+5;
int maxpos[MXN];
int bigger[MXN];
int a[MXN];
vector<int>ls;
void Main(int avg){
    int n;cin>>n;
    ls.clear();
    for(int i=1;i<=n;i++) maxpos[i]=bigger[i]=0;
    for(int i=1;i<=n;i++) scanf("%d",&a[i]),ls.push_back(a[i]);
    sort(ls.begin(),ls.end());
    ls.erase(unique(ls.begin(),ls.end()),ls.end());
    for(int i=1;i<=n;i++){
        int id=lower_bound(ls.begin(),ls.end(),a[i])-ls.begin()+1;
        maxpos[id]= i;
    }
    int sz=SZ(ls);
    for(int i=2;i<=sz;i++){
        if(maxpos[i]>maxpos[i-1]) bigger[i]= 1;
    }
    int mx=1,now=1;
    for(int i=2;i<=sz;i++){
        if(bigger[i]) now++;
        else mx=max(now,mx),now=1;
    }
int zz;
    mx=max(now,mx);
    cout<<sz-mx<<'\n';
}
int main(){

    int cas;cin>>cas;for(int i=1;i<=cas;i++)Main(i);
    return 0;
}


/*   Author : Rshs
 *   Data : 2019-10-07-00.17
 */
#include<bits/stdc++.h>
using namespace std;
#define FI first
#define SE second
#define LL long long
#define MP make_pair
#define PII pair<int,int>
#define SZ(a) (int)a.size()
const double pai = acos(-1);
const double eps = 1e-10;
const LL mod = 1e9+7;
const int MXN = 1e6+5;
int maxpos[MXN];
int bigger[MXN];
int a[MXN];
vector<int>ls;
void Main(int avg){
    int n;cin>>n;
    ls.clear();
    for(int i=1;i<=n;i++) maxpos[i]=bigger[i]=0;
    for(int i=1;i<=n;i++) scanf("%d",&a[i]),ls.push_back(a[i]);
    sort(ls.begin(),ls.end());
    ls.erase(unique(ls.begin(),ls.end()),ls.end());
    for(int i=1;i<=n;i++){
        int id=lower_bound(ls.begin(),ls.end(),a[i])-ls.begin()+1;
        maxpos[id]=i;
    }
    int sz=SZ(ls);
    for(int i=2;i<=sz;i++){
        if(maxpos[i]>maxpos[i-1]) bigger[i]=1;
    }
    int mx=1,now=1;
    for(int i=2;i<=sz;i++){
        if(bigger[i]) now++;
        else mx=max(now,mx),now=1;
    }
    mx=max(now,mx);
    cout<<sz-mx<<'\n';
}
int main(){
    int cas;cin>>cas;for(int i=1;i<=cas;i++)Main(i);
    return 0;
}


#include<bits/stdc++.h>

using namespace std;

/// Typedef
typedef long long ll;

#define sc1(a) scanf("%lld",&a)
#define sc2(a,b) scanf("%lld %lld",&a,&b)

#define pf1(a) printf("%lld\n",a)
#define pf2(a,b) printf("%lld %lld\n",a,b)

#define vpnt(ans) for(ll i = 0; i < ans.size(); i++) cout << ans[i] << (i + 1 < ans.size() ? ' ' : '\n');
#define apnt(arr, num) for(ll i = 0; i < num; i++) cout << arr[i] << (i + 1 < num ? ' ' : '\n');

#define mx 100007
#define mod 100000007
#define PI acos(-1.0)
#define size1 300100

#define no cout << "NO" << endl
#define yes cout << "YES" << endl
#define clr(x,a)    memset(x,a,sizeof(x))

#define pb push_back
#define ff first
#define ss second
#define mp make_pair
#define case cout << "Case " << t++ << ": ";

typedef vector <ll> vll;
typedef map <ll, ll> mll;
typedef pair <ll, ll> pll;
typedef vector <pair <ll, ll> > vpll;
typedef set <ll> sll;

ll arr[size1];

int main()
{

    ll m, n, tc, num, t = 1;

    sc1(tc);

    while (tc--) {
        sc1(num);

        sll st;
        mll firstpos, lastpos;

        for (ll i = 1; i <= num; ++i) {
            sc1(arr[i]);
            st.insert(arr[i]);

            if(firstpos[arr[i]] == 0)
                firstpos[arr[i]] = i;
            lastpos[arr[i]] = i;
        }

        vll vc;
        for (auto it : st)
            vc.push_back(it);

        ll ext = 0, cnt = 0, indx = 0;
        for (ll i = 0; i < vc.size(); ++i) {
            if(firstpos[vc[i]] > indx) {
                cnt++;
                indx = lastpos[vc[i]];
            }
            else {
                ext = max(ext, cnt);
                indx = lastpos[vc[i]];
                cnt = 1;
            }
        }
        ext = max(ext, cnt);

        ll ans = (ll)vc.size() - ext;

        pf1(ans);
    }
}


#include<bits/stdc++.h>

using namespace std;

/// Typedef
typedef long long ll;

#define sc1(a) scanf("%lld",&a)
#define sc2(a,b) scanf("%lld %lld",&a,&b)

#define pf1(a) printf("%lld\n",a)
#define pf2(a,b) printf("%lld %lld\n",a,b)

#define vpnt(ans) for(ll i = 0; i < ans.size(); i++) cout << ans[i] << (i + 1 < ans.size() ? ' ' : '\n');
#define apnt(arr, num) for(ll i = 0; i < num; i++) cout << arr[i] << (i + 1 < num ? ' ' : '\n');

#define mx 100007
#define mod 100000007
#define PI acos(-1.0)
#define size1 300100

#define no cout << "NO" << endl
#define yes cout << "YES" << endl
#define clr(x,a)    memset(x,a,sizeof(x))

#define pb push_back
#define ff first
#define ss second
#define mp make_pair
#define case cout << "Case " << t++ << ": ";

typedef vector <ll> vll;
typedef map <ll, ll> mll;
typedef pair <ll, ll> pll;
typedef vector <pair <ll, ll> > vpll;
typedef set <ll> sll;

ll arr[size1];

int main()
{

    ll m, n, tc, num, t = 1;

    sc1(tc);

    while (tc--) {
        sc1(num);

        sll st;
        mll firstpos, lastpos;

        for (ll i = 0; i < num; ++i) {
            sc1(arr[i]);
            st.insert(arr[i]);

            if(firstpos[arr[i]] == 0)
                firstpos[arr[i]] = i;
            lastpos[arr[i]] = i;
        }

        vll vc;
        for (auto it : st)
            vc.push_back(it);

        ll ext = 0, cnt = 0, indx = 0;
        for (ll i = 0; i < vc.size(); ++i) {
            if(firstpos[vc[i]] > indx) {
                cnt++;
                indx = lastpos[vc[i]];
            }
            else {
                ext = max(ext, cnt);
                indx = lastpos[vc[i]];
                cnt = 1;
            }
        }
        ext = max(ext, cnt);

        ll ans = (ll)st.size() - ext;

        pf1(ans);
    }
}


#include<bits/stdc++.h>

using namespace std;

/// Typedef
typedef long long ll;

#define sc1(a) scanf("%lld",&a)
#define sc2(a,b) scanf("%lld %lld",&a,&b)

#define pf1(a) printf("%lld\n",a)
#define pf2(a,b) printf("%lld %lld\n",a,b)

#define vpnt(ans) for(ll i = 0; i < ans.size(); i++) cout << ans[i] << (i + 1 < ans.size() ? ' ' : '\n');
#define apnt(arr, num) for(ll i = 0; i < num; i++) cout << arr[i] << (i + 1 < num ? ' ' : '\n');

#define mx 100007
#define mod 100000007
#define PI acos(-1.0)
#define size1 300100

#define no cout << "NO" << endl
#define yes cout << "YES" << endl
#define clr(x,a)    memset(x,a,sizeof(x))

#define pb push_back
#define ff first
#define ss second
#define mp make_pair
#define case cout << "Case " << t++ << ": ";

typedef vector <ll> vll;
typedef map <ll, ll> mll;
typedef pair <ll, ll> pll;
typedef vector <pair <ll, ll> > vpll;
typedef set <ll> sll;

ll arr[size1];

int main()
{

    ll m, n, tc, num, t = 1;

    sc1(tc);

    while (tc--) {
        sc1(num);

        sll st;
        mll firstpos, lastpos;

        for (ll i = 0; i < num; ++i) {
            sc1(arr[i]);
            st.insert(arr[i]);

            if(firstpos[arr[i]] == 0)
                firstpos[arr[i]] = i;
            lastpos[arr[i]] = i;
        }

        vll vc;
        for (auto it : st)
            vc.push_back(it);

        ll ext = 0, cnt = 0, indx = 0;
        for (ll i = 0; i < vc.size(); ++i) {
            if(firstpos[vc[i]] > indx) {
                cnt++;
                indx = lastpos[vc[i]];
            }
            else {
                ext = max(ext, cnt);
                indx = lastpos[vc[i]];
                cnt = 1;
            }
        }
        ext = max(ext, cnt);

        ll ans = (ll)vc.size() - ext;

        pf1(ans);
    }
}


#include<bits/stdc++.h>

using namespace std;

/// Typedef
typedef long long ll;

#define sc1(a) scanf("%lld",&a)
#define sc2(a,b) scanf("%lld %lld",&a,&b)

#define pf1(a) printf("%lld\n",a)
#define pf2(a,b) printf("%lld %lld\n",a,b)

#define vpnt(ans) for(ll i = 0; i < ans.size(); i++) cout << ans[i] << (i + 1 < ans.size() ? ' ' : '\n');
#define apnt(arr, num) for(ll i = 0; i < num; i++) cout << arr[i] << (i + 1 < num ? ' ' : '\n');

#define mx 100007
#define mod 100000007
#define PI acos(-1.0)
#define size1 300100

#define no cout << "NO" << endl
#define yes cout << "YES" << endl
#define clr(x,a)    memset(x,a,sizeof(x))

#define pb push_back
#define ff first
#define ss second
#define mp make_pair
#define case cout << "Case " << t++ << ": ";

typedef vector <ll> vll;
typedef map <ll, ll> mll;
typedef pair <ll, ll> pll;
typedef vector <pair <ll, ll> > vpll;
typedef set <ll> sll;

ll arr[size1];

int main()
{

    ll m, n, tc, num, t = 1;

    sc1(tc);

    while (tc--) {
        sc1(num);

        sll st;
        mll firstpos, lastpos;

        for (ll i = 1; i <= num; ++i) {
            sc1(arr[i]);
            st.insert(arr[i]);

            if(firstpos[arr[i]] == 0)
                firstpos[arr[i]] = i;
            lastpos[arr[i]] = i;
        }

        vll vc;
        for (auto it : st)
            vc.push_back(it);

        ll ext = 0, cnt = 0, indx = 0;
        for (ll i = 0; i < vc.size(); ++i) {
            if(firstpos[vc[i]] > indx) {
                cnt++;
                indx = lastpos[vc[i]];
            }
            else {
                ext = max(ext, cnt);
                indx = lastpos[vc[i]];
                cnt = 1;
            }
        }
        ext = max(ext, cnt);

        ll ans = (ll)st.size() - ext;

        pf1(ans);
    }
}


#include <bits/stdc++.h>
using namespace std;
#define pb push_back
typedef long long ll;

int main(){
	int q, n, arr[300009];
	cin>>q;
	while(q--){
		cin>>n;

		int first[n + 11] = {0};
		int last[n + 11] = {0};
		int f = 0, men = 30000000;
		for(int i = 1; i <= n; i++){
			cin>>arr[i];
			men = min(men, arr[i]);
			if(first[arr[i]] == 0){

				f++;

				first[arr[i]] = i;
			}
			last[arr[i]] = i;
		}
		int mex = 1, curl = last[men], cu = 1;

		for(int i = men + 1; i <= n; i++){
			if(first[i] != 0){

			if(first[i] > curl){
				curl = last[i];
				cu++;
				mex = max(mex, cu);
			}
			else{
				curl = last[i];
				cu = 1;
			}
			}
		}
		cout<<f - mex<<'\n';
		}
	}


#include <bits/stdc++.h>
using namespace std;
#define pb push_back
typedef long long ll;

int main(){
	int q, n, arr[300009];
	cin>>q;
	while(q--){
		cin>>n;

		int first[n + 11] = {0};
		int last[n + 11] = {0};
		int f = 0;

		for(int i = 1; i <= n; i++){
			cin>>arr[i];

			if(first[arr[i]] == 0){
				f++;

				first[arr[i]] = i;
			}
			last[arr[i]] = i;
		}
		int mex = 1, curl = last[1], cu = 1;

		for(int i = 2; i <= n; i++){
			if(first[i] != 0){

			if(first[i] > curl){
				curl = last[i];
				cu++;
				mex = max(mex, cu);
			}
			else{
				curl = last[i];
				cu = 1;
			}
			}
		}
		cout<<f - mex<<'\n';
		}
	}


#include <bits/stdc++.h>
using namespace std;
#define pb push_back
typedef long long ll;

int main(){
	int q, n, arr[300009];
	cin>>q;
	while(q--){
		cin>>n;
		for(int i = 1; i <= n; i++){
			cin>>arr[i];
		}
		int first[300009] = {0};
		int last[300009] = {0};
		int f = 0;

		for(int i = 1; i <= n; i++){
			if(first[arr[i]] == 0){
				f++;

				first[arr[i]] = i;
			}
			last[arr[i]] = i;
		}
		int mex = 1, curl = last[1], cu = 1;

		for(int i = 2; i <= n; i++){
			if(first[i] != 0){

			if(first[i] > curl){
				curl = last[i];
				cu++;
				mex = max(mex, cu);
			}
			else{
				curl = last[i];
				cu = 1;
			}
			}
		}
		cout<<f - mex<<'\n';
		}
	}


#include <bits/stdc++.h>
using namespace std;
#define pb push_back
typedef long long ll;

int main(){
	int q, n, arr[300009], dddddd;
	cin>>q;
	while(q--){
		cin>>n;
		for(int i = 1; i <= n; i++){
			cin>>arr[i];
		}
		int first[300009] = {0};
		int last[300009] = {0};
		int f = 0;

		for(int i = 1; i <= n; i++){
			if(first[arr[i]] == 0){
				f++;

				first[arr[i]] = i;
			}
			last[arr[i]] = i;
		}
		int mex = 1, curl = last[1], cu = 1;

		for(int i = 2; i <= n; i++){
			if(first[i] != 0){

			if(first[i] > curl){
				curl = last[i];
				cu++;
				mex = max(mex, cu);
			}
			else{
				curl = last[i];
				cu = 1;
			}
			}
		}
		cout<<f - mex<<'\n';
		}
	}


#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#if __cplusplus >= 201103L
#include <unordered_map>
#include <unordered_set>
#endif
#include <vector>
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define LONG_LONG_MAX 9223372036854775807LL
#define pblank putchar(' ')
#define ll LL
#define fastIO ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int, int> P;
int n, m, k;
const int maxn = 3e5 + 10;
template <class T>
inline T read()
{
    int f = 1;
    T ret = 0;
    char ch = getchar();
    while (!isdigit(ch))
    {
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while (isdigit(ch))
    {
        ret = (ret << 1) + (ret << 3) + ch - '0';
        ch = getchar();
    }
    ret *= f;
    return ret;
}
template <class T>
inline void write(T n)
{
    if (n < 0)
    {
        putchar('-');
        n = -n;
    }
    if (n >= 10)
    {
        write(n / 10);
    }
    putchar(n % 10 + '0');
}
template <class T>
inline void writeln(const T &n)
{
    write(n);
    puts("");
}
vector<int> a;
int l[maxn], r[maxn];
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    // freopen("out.txt","w", stdout);
#endif
    int t = read<int>();
    while (t--)
    {
        n = read<int>();
        a.clear();
        for (int i = 1; i <= n; i++)
            l[i] = 1e9, r[i] = 0;
        for (int i = 1; i <= n; i++)
        {
            int x = read<int>();
            a.emplace_back(x);
            if (l[x] == 1e9)
                l[x] = i;
            r[x] = i;
        }
        sort(a.begin(), a.end());
        a.erase(unique(a.begin(), a.end()), a.end());
        int sz = a.size();
        int res = 0;
        int cur = 1;
        for (int i = 1; i < sz; i++){
            if (l[a[i]] > r[a[i-1]])
                ++cur;
            else
                cur = 1;
            res = max(res, cur);
        }
        writeln(sz-res);
    }
    return 0;
}


#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#if __cplusplus >= 201103L
#include <unordered_map>
#include <unordered_set>
#endif
#include <vector>
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define LONG_LONG_MAX 9223372036854775807LL
#define pblank putchar(' ')
#define ll LL
#define fastIO ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int, int> P;
int n, m, k;
const int maxn = 3e5 + 10;
template <class T>
inline T read()
{
    int f = 1;
    T ret = 0;
    char ch = getchar();
    while (!isdigit(ch))
    {
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while (isdigit(ch))
    {
        ret = (ret << 1) + (ret << 3) + ch - '0';
        ch = getchar();
    }
    ret *= f;
    return ret;
}
template <class T>
inline void write(T n)
{
    if (n < 0)
    {
        putchar('-');
        n = -n;
    }
    if (n >= 10)
    {
        write(n / 10);
    }
    putchar(n % 10 + '0');
}
template <class T>
inline void writeln(const T &n)
{
    write(n);
    puts("");
}
vector<int> a;
int l[maxn], r[maxn];
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    // freopen("out.txt","w", stdout);
#endif
    int t = read<int>();
    while (t--)
    {
        n = read<int>();
        a.clear();
        for (int i = 1; i <= n; i++)
            l[i] = 1e9, r[i] = 0;
        for (int i = 1; i <= n; i++)
        {
            int x = read<int>();
            a.emplace_back(x);
            if (l[x] == 1e9)
                l[x] = i;
            r[x] = i;
        }
        sort(a.begin(), a.end());
        a.erase(unique(a.begin(), a.end()), a.end());
        int sz = a.size();
        int res = 0;
        for (int i = 1; i < sz; i++)
            if (l[a[i]] < r[a[i - 1]])
                ++res;
        writeln(res);
    }
    return 0;
}