#include <bits/stdc++.h>
#define ll long long
using namespace std;
#define ll long long
int a[100005];
map<ll,int> b;
map<ll,vector<int> > v;
int main(){
int t,n;
scanf("%d",&t);
while(t--){
int ls = 0;
scanf("%d",&n);
priority_queue<int> q;
b.clear();
q.push(0);
for(int i=1;i<=n;i++)v.clear();
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
if(b[a[i]]==0)q.push(a[i]);
b[a[i]]++;v[a[i]].push_back(i);
}
int i;
int ans = 0;
ls = q.top(); //当前
q.pop();
int nx = q.top();//次大
int flag = 0;
while(nx!=0){
int id=v[ls][0];
if(flag==0){
for(int i=0;i<v[nx].size();i++){
if(v[nx][i]>id)
{ ans+=v[nx].size()-i;break;
}
}
}else {
ans +=v[nx].size();
}
if(ans!=0)flag=1;
//printf("%d %d %d\n",ls,nx,id);
ls = nx;
q.pop();
nx = q.top();
}
q.pop();
cout << ans <<endl;
}
}