#include<bits/stdc++.h>
#define ll long long
#define pb push_back
#define ff first
#define ss second
#define debug cout<<"here\n" 
#define MOD 1000000007

const int MAXN = 2e5 +15;
using namespace std;

int A[MAXN], pre[MAXN], mpre[MAXN];
int st[4*MAXN][2];

void update(int f, int v, int tl, int tr, int p, int x){
	if(tl == tr){
		st[v][f] = x;
		return;
	}
	int tm = (tl + tr)/2;
	if(p <= tm){
		update(f, 2*v, tl , tm, p, x);
	}
	else update(f, 2*v + 1, tm+1,tr, p, x);
	st[v][f] = max(st[2*v][f], st[2*v+1][f]);
}
int rmax(int f, int v, int tl, int tr, int l, int r){
	if(l > r ) return 0;
	if(tl == l && tr == r) return st[v][f];
	int tm = (tl+tr)/2;
	return max(rmax(f,2*v, tl, tm, l, min(r,tm)), rmax(f,2*v + 1, tm+1, tr, max(tm+1,l),r));
}

void ok(int n){
	for(int i=0; i<=n; i++){
		pre[i] = 0;
		mpre[i] = 0;
	}
	for(int i=0; i<= 4*n; i++){
		st[i][0] = st[i][1] = 0;
	}
}
void solve(){	
	int n; cin>>n;
	ok(n);
	map<int, int> mp;
	vector<int> v;
	for(int i=1; i<=n; i++){
		cin>>A[i];
		v.pb(A[i]);
	}
	sort(v.begin(), v.end()	);
	mp[v[0]] = 1;
	for(int i=1; i<n; i++) mp[v[i]] = mp[v[i-1]] + (v[i] != v[i-1]);
	for(int i=1; i<=n; i++) A[i] = mp[A[i]];

	//coordinate compressed
	stack<int> st;
	st.push(1);
	for(int i=2; i<=n; i++){
		while(!st.empty()){
			int p = st.top();
			if(A[p] <= A[i]){
				pre[i] = p;
				break;
			}
			else st.pop();
		}
		st.push(i);
	}
	while(!st.empty()) st.pop();
	st.push(1);
	for(int i=2; i<=n; i++){
		while(!st.empty()){
			int p = st.top();
			if(A[p] >= A[i]){
				mpre[i] = p;
				break;
			}
			else st.pop();
		}
		st.push(i);
	}
	//pre and mpre made
	ll ans = 0; int L = 0; 
	for(int i=1; i<= n; i++){
		int x = A[i];
		int las = max(rmax(0,1,1,n,1,A[i]), rmax(1,1,1,n,A[i],n));
		L = max(L, las);
		//cout<<A[i]<<" "<<pre[i]<<" "<<mpre[i]<<" : "<<rmax(0,1,1,n,1,A[i])<<" "<<rmax(1,1,1,n,A[i],n)<<"\n";
		ans += (i - L);
		update(0,1,1,n,x,pre[i]);
		update(1,1,1,n,x,mpre[i]);
	}
	cout<<ans;


}
 
int main(){
	ios_base::sync_with_stdio(false);
	cout.tie(0); cin.tie(0);	
	cout<<fixed<<setprecision(12);

	int t =1; cin>>t;
	for(int i=1; i<= t; i++){
		solve();
		cout<<"\n";
	}
	
	return 0;
}
/* stuff you should look for
	* int overflow, array bounds
	* special cases (n=1?)
	* do smth instead of nothing and stay organized
	* WRITE STUFF DOWN
	* DON'T GET STUCK ON ONE APPROACH
*/