#include<bits/stdc++.h>
#pragma optimize("O2")
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N=2e5+10;
ll t;
ll a[N];
void solve()
{
ll n;
cin>>n;
for(ll i=1;i<=n;i++)
{
cin>>a[i];
}
vector<ll> L{0};
a[0]=a[n+1]=2e9+10;
ll ans=0;
for(ll i=1;i<=n;i++)
{
while(L.size()&&a[L.back()]<a[i])
{
L.pop_back();
}
if(a[i]!=L.back())ans+=i-L.back()-1;
L.push_back(i);
}
vector<ll>R{n+1};
for(ll i=n;i>=1;i--)
{
while(R.size()&&a[i]>a[R.back()])
{
R.pop_back();
}
(ifa[i]!=R.back())ans+=R.back()-i-1;
R.push_back(i);
}
cout<<ans<<'\n';
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>t;
while(t--)
{
solve();
}
return 0;
}