Suppose you have two points $p = (x_p, y_p)$ and $q = (x_q, y_q)$. Let's denote the Manhattan distance between them as $d(p, q) = |x_p - x_q| + |y_p - y_q|$.

Let's say that three points $p$, $q$, $r$ form a bad triple if $d(p, r) = d(p, q) + d(q, r)$.

Let's say that an array $b_1, b_2, \dots, b_m$ is good if it is impossible to choose three distinct indices $i$, $j$, $k$ such that the points $(b_i, i)$, $(b_j, j)$ and $(b_k, k)$ form a bad triple.

You are given an array $a_1, a_2, \dots, a_n$. Calculate the number of good subarrays of $a$. A subarray of the array $a$ is the array $a_l, a_{l + 1}, \dots, a_r$ for some $1 \le l \le r \le n$.

Note that, according to the definition, subarrays of length $1$ and $2$ are good.


-----Input-----

The first line contains one integer $t$ ($1 \le t \le 5000$) — the number of test cases.

The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of array $a$.

The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$).

It's guaranteed that the sum of $n$ doesn't exceed $2 \cdot 10^5$.


-----Output-----

For each test case, print the number of good subarrays of array $a$.


-----Examples-----

Input
3
4
2 4 1 3
5
6 9 1 9 6
2
13 37
Output
10
12
3


-----Note-----

In the first test case, it can be proven that any subarray of $a$ is good. For example, subarray $[a_2, a_3, a_4]$ is good since it contains only three elements and:

$d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3$ $<$ $d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7$;

$d((a_2, 2), (a_3, 3))$ $<$ $d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3))$;

$d((a_3, 3), (a_4, 4))$ $<$ $d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4))$;

In the second test case, for example, subarray $[a_1, a_2, a_3, a_4]$ is not good, since it contains a bad triple $(a_1, 1)$, $(a_2, 2)$, $(a_4, 4)$:

$d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6$;

$d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4$;

$d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2$;

So, $d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4))$.

Difficulty: MEDIUM_HARD
Tags: Geometry

Complete search

Implementation

Greedy algorithms
Skill types: Complete search

Greedy algorithms

Starter code:

Solutions:
from math import nan, isnan

def readline():
	return map(int, input().split())

def is_good(x, y, z):
	return (y - x) * (y - z) > 0

def solve():
	n = int(input())
	ans = n + (n - 1)
	(p, q, r) = (nan, nan, nan)
	for k in readline():
		if is_good(q, r, k):
			ans += 1
			if is_good(p, q, r) and is_good(p, q, k) and is_good(p, r, k):
				ans += 1
		(p, q, r) = (q, r, k)
	print(ans)

def main():
	t = int(input())
	for __ in range(t):
		solve()
main()


from itertools import combinations
from sys import stdin
input = stdin.readline

def check(d):
	for i in range(4):
		b = d[:i] + d[i + 1:]
		if b == sorted(b) or b == sorted(b, reverse=True):
			return False
	return True
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 2 * n - 1
	for i in range(n - 2):
		b = a[i:i + 3]
		if not (b == sorted(b) or b == sorted(b, reverse=True)):
			ans += 1
	for i in range(n - 3):
		b = a[i:i + 4]
		if check(b):
			ans += 1
	print(ans)


def check(a, b, c):
	if a <= b and b <= c or (a >= b and b >= c):
		return True
	else:
		return False
t = int(input())
for _ in range(t):
	n = int(input())
	a = [0] + list(map(int, input().split()))
	w = n + n - 1
	x = 0
	if n >= 3:
		x += n - 2
		for i in range(1, n - 1):
			if check(a[i], a[i + 1], a[i + 2]):
				x -= 1
	y = 0
	if n >= 4:
		y += n - 3
		for i in range(1, n - 2):
			if check(a[i], a[i + 1], a[i + 2]):
				y -= 1
			elif check(a[i], a[i + 1], a[i + 3]):
				y -= 1
			elif check(a[i], a[i + 2], a[i + 3]):
				y -= 1
			elif check(a[i + 1], a[i + 2], a[i + 3]):
				y -= 1
	answer = w + x + y
	print(answer)


import sys, math, io, os, time, itertools, collections
mod = 10 ** 9 + 7
sys.setrecursionlimit(10000)
i = sys.stdin.readline
global start, end

def isin(l, x):
	left = 0
	right = len(l) - 1
	if x < l[0]:
		return -1
	while left <= right:
		mid = left + (right - left) // 2
		if l[mid] == x:
			return mid
		elif l[mid] < x:
			ans = mid
			left = mid + 1
		else:
			right = mid - 1
	return ans

def ispal(l):
	n = len(l)
	for i in range(n // 2 + 1):
		if l[i] != l[n - i - 1]:
			return False
	return True

def ccarray(l):
	d = {l[k]: k for k in range(len(l))}
	m = sorted(d)
	return [d[m[k]] for k in range(len(l))]

def is_prime(n):
	if n <= 3:
		return n > 1
	if n % 2 == 0 or n % 3 == 0:
		return False
	k = 5
	while k ** 2 <= n:
		if n % k == 0 or n % (k + 2) == 0:
			return False
		k += 6
	return True

def sieve(n):
	prime = [True for k in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for k in range(p * p, n + 1, p):
				prime[k] = False
		p += 1

def main():
	n = int(i())
	a = [int(k) for k in i().split()]
	if n == 1:
		tot = 1
	elif n == 2:
		tot = 3
	elif n == 3:
		tot = 6
		if a[0] >= a[1] >= a[2] or a[0] <= a[1] <= a[2]:
			tot -= 1
	else:
		tot = 4 * n - 6
		for k in range(n - 2):
			arr = a[k:k + 3]
			if arr[0] >= arr[1] >= arr[2] or arr[0] <= arr[1] <= arr[2]:
				tot -= 1
		for k in range(n - 3):
			arr = a[k:k + 4]
			if arr[0] >= arr[1] >= arr[2] or arr[0] <= arr[1] <= arr[2] or arr[0] >= arr[1] >= arr[3] or (arr[0] <= arr[1] <= arr[3]) or (arr[0] >= arr[2] >= arr[3]) or (arr[0] <= arr[2] <= arr[3]) or (arr[1] >= arr[2] >= arr[3]) or (arr[1] <= arr[2] <= arr[3]):
				tot -= 1
	sys.stdout.write(str(tot) + '\n')
t = 1
t = int(i())
start = time.perf_counter()
for _ in range(t):
	main()
end = time.perf_counter()


one = 1
for _ in range(int(input())):
	zero = 0
	n = int(input())
	one = 1
	a = list(map(int, input().split()))
	zero = 0
	ans = n + n - 1
	one = 1
	for i in range(0, n - 2):
		if a[i] <= a[i + 1] <= a[i + 2] or a[i] >= a[i + 1] >= a[i + 2]:
			one = 1
			continue
		zero = 0
		ans += 1
		one = 1
	for i in range(0, n - 3):
		zero = 0
		if min(a[i], a[i + 2]) <= a[i + 1] <= max(a[i], a[i + 2]):
			one = 1
			continue
		zero = 0
		if min(a[i], a[i + 3]) <= a[i + 1] <= max(a[i], a[i + 3]):
			one = 1
			continue
		zero = 0
		if min(a[i], a[i + 3]) <= a[i + 2] <= max(a[i], a[i + 3]):
			one = 1
			continue
		zero = 0
		if min(a[i + 1], a[i + 3]) <= a[i + 2] <= max(a[i + 1], a[i + 3]):
			one = 1
			continue
		zero = 0
		ans += 1
		one = 1
	print(ans)
	zero = 0


def _sum_(n):
	res = 0
	for i in range(1, min(5, n + 1)):
		res += n + 1 - i
	return res

def test(b):
	for i in range(4):
		for j in range(i + 1, 4):
			for k in range(j + 1, 4):
				if b[i] <= b[j] <= b[k] or b[i] >= b[j] >= b[k]:
					return True
	return False
for q in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = _sum_(n)
	for i in range(2, n):
		if a[i - 2] <= a[i - 1] <= a[i]:
			ans -= 1
		elif a[i - 2] >= a[i - 1] >= a[i]:
			ans -= 1
	for i in range(n - 3):
		if test(a[i:i + 4]):
			ans -= 1
	print(ans)


t = int(input())
for test in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = 2 * n - 1
	for i in range(n - 2):
		a = arr[i]
		b = arr[i + 1]
		c = arr[i + 2]
		if b > max(a, c) or b < min(a, c):
			ans += 1
	for i in range(n - 3):
		a = arr[i]
		b = arr[i + 1]
		c = arr[i + 2]
		d = arr[i + 3]
		if max(a, d) < max(b, c) and min(a, d) > min(b, c):
			ans += 1
	print(ans)


t = int(input())

def check3(a, b, c):
	return (a - b) * (c - b) > 0

def check4(a, b, c, d):
	return check3(a, b, c) and check3(a, b, d) and check3(a, c, d) and check3(b, c, d)
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	res = n + n - 1
	for i in range(n - 2):
		if check3(a[i], a[i + 1], a[i + 2]):
			res += 1
	for i in range(n - 3):
		if check4(a[i], a[i + 1], a[i + 2], a[i + 3]):
			res += 1
	print(res)


import sys
from math import cos, pi, ceil, pi, tan, floor, gcd, sqrt, log2, factorial, log10
from collections import Counter
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase
from statistics import mean, median, mode
alpha = ascii_lowercase
beta = ascii_uppercase

def nextPowerOf2(n):
	p = 1
	if n and (not n & n - 1):
		return n
	while p < n:
		p <<= 1
	return p

def get_Divisors(n):
	arr = []
	i = 1
	while i <= sqrt(n):
		if n % i == 0:
			if n / i == i:
				arr.append(i)
			else:
				arr.append(i)
				arr.append(n // i)
		i = i + 1
	return arr

def isprime(n):
	if n == 1:
		return 0
	i = 2
	while i * i <= n:
		if n % i == 0:
			return 0
		i += 1
	return 1

def Sieve(n):
	prime = [True for i in range(n + 1)]
	prime[0] = False
	prime[1] = False
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def main():
	for ttt in range(int(input())):
		n = int(input())
		arr = list(map(int, input().split()))
		ans = 2 * n - 1
		for i in range(n - 2):
			if arr[i] <= arr[i + 1] <= arr[i + 2] or arr[i] >= arr[i + 1] >= arr[i + 2]:
				pass
			else:
				ans += 1
		for i in range(n - 3):
			if arr[i] <= arr[i + 1] <= arr[i + 2] or arr[i] >= arr[i + 1] >= arr[i + 2]:
				pass
			elif arr[i] <= arr[i + 1] <= arr[i + 3] or arr[i] >= arr[i + 1] >= arr[i + 3]:
				pass
			elif arr[i + 1] <= arr[i + 2] <= arr[i + 3] or arr[i + 1] >= arr[i + 2] >= arr[i + 3]:
				pass
			elif arr[i] <= arr[i + 2] <= arr[i + 3] or arr[i] >= arr[i + 2] >= arr[i + 3]:
				pass
			else:
				ans += 1
		print(ans)
main()


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	dp = [0 for i in range(n)]
	for k in range(n):
		maxs = [[a[k], k]]
		mins = [[a[k], k]]
		cnt = 1
		if k >= n - 2:
			cnt = n - k
		else:
			for pro in range(k + 1, min(n, k + 5)):
				if a[pro] >= a[k]:
					maxs.append([a[pro], pro])
				if a[pro] <= a[k]:
					mins.append([a[pro], pro])
				if len(maxs) > 2:
					if maxs[-1][0] >= maxs[-2][0]:
						break
					if mins:
						if mins[-1][1] > maxs[-1][1]:
							break
				if len(mins) > 2:
					if mins[-1][0] <= mins[-2][0]:
						break
					if maxs:
						if maxs[-1][1] > mins[-1][1]:
							break
				if len(maxs) == 4:
					if maxs[-1] <= maxs[-2] <= maxs[-3]:
						break
				if len(mins) == 4:
					if mins[-1] >= mins[-2] >= mins[-3]:
						break
				cnt += 1
		dp[k] = cnt
	print(sum(dp))


import sys
input = lambda : sys.stdin.readline().rstrip()
T = int(input())
for _ in range(T):
	N = int(input())
	A = [int(a) for a in input().split()]
	ans = N + N - 1
	for i in range(N - 2):
		(a, b, c) = (A[i], A[i + 1], A[i + 2])
		if a > b < c or a < b > c:
			ans += 1
	for i in range(N - 3):
		(a, b, c, d) = (A[i], A[i + 1], A[i + 2], A[i + 3])
		if b < a < c and b < d < c or (c < a < b and c < d < b):
			ans += 1
	print(ans)


t = int(input())
for o in range(t):
	ans = 0
	n = int(input())
	l = list(map(int, input().strip().split()))
	if n == 1:
		print(1)
		continue
	elif n == 2:
		print(3)
		continue
	for i in range(n - 2):
		ans += 2
		b0 = l[i]
		b1 = l[i + 1]
		lower = -1000000000000000
		upper = 1000000000000000
		if b0 == b1:
			continue
		elif b0 < b1:
			upper = b1
		else:
			lower = b1
		b2 = l[i + 2]
		if b2 > lower and b2 < upper:
			ans += 1
		else:
			continue
		if b2 > b0 and b2 < b1:
			continue
		if b2 < b0 and b2 > b1:
			continue
		if b2 > b0:
			upper = b2
		if b2 < b0:
			lower = b2
		if b2 == b0 or b2 == b1:
			continue
		if i + 3 < n:
			b3 = l[i + 3]
			if b3 > lower and b3 < upper:
				ans += 1
	ans += 3
	print(ans)


for _ in range(int(input())):
	n = int(input())
	nums = list(map(int, input().split()))
	ans = n * 2 - 1
	for i in range(2, n):
		if nums[i - 1] < nums[i - 2]:
			ans += nums[i - 1] < nums[i]
		elif nums[i - 1] > nums[i - 2]:
			ans += nums[i - 1] > nums[i]
	for i in range(3, n):
		(a, b) = (nums[i - 1], nums[i - 2])
		if a > b:
			(a, b) = (b, a)
		if a < nums[i - 3] < b and a < nums[i] < b:
			ans += 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(n):
		if i + 2 < n:
			if a[i] == a[i + 1]:
				continue
			elif a[i] < a[i + 1]:
				if a[i + 1] <= a[i + 2]:
					continue
				else:
					ans += 1
					if i + 3 < n:
						if a[i] <= a[i + 2]:
							continue
						elif a[i + 2] >= a[i + 3] or a[i + 1] <= a[i + 3]:
							continue
						else:
							ans += 1
			elif a[i + 1] >= a[i + 2]:
				continue
			else:
				ans += 1
				if i + 3 < n:
					if a[i] >= a[i + 2]:
						continue
					elif a[i + 2] <= a[i + 3] or a[i + 1] >= a[i + 3]:
						continue
					else:
						ans += 1
	print(ans + n + (n - 1))


import sys
input = sys.stdin.readline

def main():
	t = int(input())
	INF = 1001001001
	for _ in range(t):
		n = int(input())
		A = list(map(int, input().split()))
		ans = n + n - 1
		for i in range(n - 2):
			if check(A[i], i, A[i + 1], i + 1, A[i + 2], i + 2):
				ans += 1
		for i in range(n - 3):
			a = check(A[i], i, A[i + 1], i + 1, A[i + 2], i + 2)
			b = check(A[i], i, A[i + 1], i + 1, A[i + 3], i + 3)
			c = check(A[i], i, A[i + 2], i + 2, A[i + 3], i + 3)
			d = check(A[i + 1], i + 1, A[i + 2], i + 2, A[i + 3], i + 3)
			if a and b and c and d:
				ans += 1
		print(ans)

def check(ai, i, aj, j, ak, k):
	if abs(ak - ai) + abs(k - i) == abs(aj - ai) + abs(j - i) + abs(ak - aj) + abs(k - j):
		return False
	else:
		return True
main()


def Manhattan_distance(p, q):
	return abs(p[0] - q[0]) + abs(p[1] - q[1])

def is_bad_triple(p, q, r):
	x = Manhattan_distance(p, q)
	y = Manhattan_distance(p, r)
	z = Manhattan_distance(r, q)
	X = [x, y, z]
	return X[0] == X[1] + X[2] or X[1] == X[0] + X[2] or X[2] == X[1] + X[0]
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 1:
		print(1)
	elif n == 2:
		print(3)
	else:
		b = [(a[i], i + 1) for i in range(n)]
		dp = [2 for i in range(n)]
		dp[-1] = 1
		for i in range(n - 1, -1, -1):
			for l in range(3, n + 1):
				if i + l <= n and dp[i] >= l - 1 and (dp[i + 1] >= l - 1):
					flag = True
					for j in range(i + 1, i + l - 1):
						if is_bad_triple(b[i], b[j], b[i + l - 1]):
							flag = False
							break
					if flag:
						dp[i] = l
				else:
					break
		ans = sum(dp)
		print(ans)


import sys

def check_triple(x, y, z):
	return (x - y) * (y - z) < 0

def solve(arr):
	n = len(arr)
	base = n + (n - 1)
	triple = 0
	for i in range(2, n):
		to_check = arr[i - 2:i + 1]
		if check_triple(*to_check):
			triple += 1
	quadro = 0
	for i in range(3, n):
		candidates = arr[i - 3:i + 1]
		found = False
		for j in range(4):
			to_check = candidates[:j] + candidates[j + 1:]
			if not check_triple(*to_check):
				found = True
				break
		if not found:
			quadro += 1
	return base + triple + quadro

def main():
	outputs = []
	fin = sys.stdin
	N = int(fin.readline())
	for _ in range(N):
		n = int(fin.readline())
		arr = list(map(int, fin.readline().split()))
		outputs.append(solve(arr))
	print('\n'.join(map(str, outputs)))
main()


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	res = 0
	for j in range(n):
		kx = min(j + 4, n)
		for k in range(j, kx):
			bl = True
			for l in range(j, k):
				for m in range(l + 1, k):
					if a[l] <= a[m] <= a[k] or a[l] >= a[m] >= a[k]:
						bl = False
						break
				if not bl:
					break
			else:
				res += 1
				continue
			break
	print(res)


import sys
import bisect
from bisect import bisect_left as lb
from bisect import bisect_right as rb
input_ = lambda : sys.stdin.readline().strip('\r\n')
from math import log
from math import gcd
from math import atan2, acos
from random import randint
sa = lambda : input_()
sb = lambda : int(input_())
sc = lambda : input_().split()
sd = lambda : list(map(int, input_().split()))
sflo = lambda : list(map(float, input_().split()))
se = lambda : float(input_())
sf = lambda : list(input_())
flsh = lambda : sys.stdout.flush()
mod = 10 ** 9 + 7
mod1 = 998244353
gp = []
cost = []
dp = []
mx = []
ans1 = []
ans2 = []
special = []
specnode = []
a = 0
kthpar = []

def dfs2(root, par):
	if par != -1:
		dp[root] = dp[par] + 1
	for i in range(1, 20):
		if kthpar[root][i - 1] != -1:
			kthpar[root][i] = kthpar[kthpar[root][i - 1]][i - 1]
	for child in gp[root]:
		if child == par:
			continue
		kthpar[child][0] = root
		dfs(child, root)
ans = 0
b = []
vis = []
tot = 0
time = []
time1 = []
adj = []
mx = -1
eps = 1e-07

def dfs(a, b, p, c):
	if a == b:
		return c
	for (i, j) in adj[a]:
		if i == p:
			continue
		temp = dfs(i, b, a, c + j)
		if dfs(i, b, a):
			mx = max(i, mx)
			return 1
adj = []
ans = []

def dfs(root, par, v):
	global adj, ans, abe
	tot = v
	for (child, val) in adj[root]:
		if par == child:
			continue
		tot |= dfs(child, root, val)
	ans[root] = tot
	return tot
abe = 0

def traverse(root, par):
	global adj, ans, abe
	for (child, val) in adj[root]:
		if par == child:
			continue
		if ans[child] == 0:
			abe += 1
		else:
			traverse(child, root)

def hnbhai(tc):
	n = sb()
	a = sd()
	ans = 2 * n - 1
	for i in range(n - 2):
		temp = [a[i], a[i + 1], a[i + 2]]
		if temp == list(sorted(temp)):
			continue
		if temp == list(sorted(temp, reverse=True)):
			continue
		ans += 1
	for i in range(n - 3):
		temp = [a[i], a[i + 1], a[i + 2]]
		temp1 = [a[i], a[i + 1], a[i + 3]]
		temp2 = [a[i + 1], a[i + 2], a[i + 3]]
		temp3 = [a[i], a[i + 2], a[i + 3]]
		if temp == list(sorted(temp)) or temp3 == list(sorted(temp3)) or temp1 == list(sorted(temp1)) or (temp2 == list(sorted(temp2))):
			continue
		if temp == list(sorted(temp, reverse=True)) or temp3 == list(sorted(temp3, reverse=True)) or temp1 == list(sorted(temp1, reverse=True)) or (temp2 == list(sorted(temp2, reverse=True))):
			continue
		ans += 1
	print(ans)
for _ in range(sb()):
	hnbhai(_ + 1)


import sys
input = sys.stdin.readline

def dist(a, b, idxa, idxb):
	return abs(a - b) + abs(idxa - idxb)

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(n):
		for j in range(i, n):
			if i + 2 <= j:
				flag = True
				for k in range(i, j):
					for l in range(k + 1, j):
						if dist(a[k], a[j], k, j) == dist(a[k], a[l], k, l) + dist(a[l], a[j], l, j):
							flag = False
				if not flag:
					break
			ans += 1
	print(ans)
	return
t = int(input())
for _ in range(t):
	solve()


n = int(input())

def analyze_4(dec, b, d):
	if d is None:
		return 3
	if not dec:
		if d >= b:
			return 3
		else:
			return 4
	elif d <= b:
		return 3
	else:
		return 4

def analyze_3(a, b, c, d=None):
	if a == b:
		return 2
	elif a < b:
		if b <= c:
			return 2
		elif c >= a or d is None or d <= c or (d >= b):
			return 3
		else:
			return analyze_4(False, b, d)
	elif b >= c:
		return 2
	elif c <= a or d is None or d >= c or (d <= b):
		return 3
	else:
		return analyze_4(True, b, d)
for _ in range(n):
	n = int(input())
	ls = list(map(int, input().split()))
	if n == 1:
		print(1)
	elif n == 2:
		print(3)
	else:
		ans = 0
		prev = 0
		for idx in range(len(ls) - 2):
			if idx + 3 < len(ls):
				seg = analyze_3(ls[idx], ls[idx + 1], ls[idx + 2], ls[idx + 3])
			else:
				seg = analyze_3(ls[idx], ls[idx + 1], ls[idx + 2], None)
			ans += seg * (seg + 1) // 2 - prev * (prev + 1) // 2
			prev = seg - 1
		if seg == 2:
			ans += 2
		print(ans)


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = n * 2 - 1
	if n < 3:
		print(ans)
	elif n == 3:
		if a[0] >= a[1] >= a[2] or a[0] <= a[1] <= a[2]:
			print(ans)
		else:
			print(ans + 1)
	else:
		for i in range(n - 2):
			if not (a[i] >= a[i + 1] >= a[i + 2] or a[i] <= a[i + 1] <= a[i + 2]):
				ans += 1
		for i in range(n - 3):
			ans += 1
			if a[i] >= a[i + 1] and (a[i + 2] <= a[i + 1] or a[i + 3] <= a[i + 1]):
				ans -= 1
			elif a[i] <= a[i + 1] and (a[i + 2] >= a[i + 1] or a[i + 3] >= a[i + 1]):
				ans -= 1
			elif a[i + 1] >= a[i + 2] >= a[i + 3] or a[i + 1] <= a[i + 2] <= a[i + 3]:
				ans -= 1
			elif a[i] >= a[i + 2] >= a[i + 3] or a[i] <= a[i + 2] <= a[i + 3]:
				ans -= 1
		print(ans)


import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	ans = n + n - 1
	invalid = set()
	for i in range(n - 2):
		x = a[i:i + 3]
		ans += 1
		if x == sorted(x) or x[::-1] == sorted(x):
			ans -= 1
			invalid.add(i)
	for i in range(n - 3):
		x = a[i:i + 4]
		if i in invalid or i + 1 in invalid:
			continue
		ans += 1
		x1 = [x[0]] + x[2:]
		x2 = x[:2] + [x[-1]]
		if x1 == sorted(x1) or x1[::-1] == sorted(x1):
			ans -= 1
		elif x2 == sorted(x2) or x2[::-1] == sorted(x2):
			ans -= 1
	print(ans)


import os
import sys
from io import BytesIO, IOBase
import math
from queue import Queue
import collections
import itertools
import bisect
import heapq
import random

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

def primeFactors(n):
	cnt = []
	while n % 2 == 0:
		cnt.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			cnt.append(i)
			n = n / i
	if n > 2:
		cnt.append(int(n))
	return cnt

def primeFactorsCount(n):
	cnt = 0
	while n % 2 == 0:
		cnt += 1
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			cnt += 1
			n = n // i
	if n > 2:
		cnt += 1
	return cnt

def isPrime(n):
	if n == 1:
		return False
	else:
		root = int(n ** 0.5)
		root += 1
		for i in range(2, root):
			if n % i == 0:
				return False
		return True

def maxPrimeFactors(n):
	maxPrime = -1
	while n % 2 == 0:
		maxPrime = 2
		n >>= 1
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			maxPrime = i
			n = n / i
	if n > 2:
		maxPrime = n
	return int(maxPrime)

def countcon(s, i):
	c = 0
	ch = s[i]
	for i in range(i, len(s)):
		if s[i] == ch:
			c += 1
		else:
			break
	return c

def lis(arr):
	n = len(arr)
	lis = [1] * n
	for i in range(1, n):
		for j in range(0, i):
			if arr[i] > arr[j] and lis[i] < lis[j] + 1:
				lis[i] = lis[j] + 1
	maximum = 0
	for i in range(n):
		maximum = max(maximum, lis[i])
	return maximum

def isSubSequence(str1, str2):
	m = len(str1)
	n = len(str2)
	j = 0
	i = 0
	while j < m and i < n:
		if str1[j] == str2[i]:
			j = j + 1
		i = i + 1
	return j == m

def maxfac(n):
	root = int(n ** 0.5)
	for i in range(2, root + 1):
		if n % i == 0:
			return n // i
	return n

def p2(n):
	c = 0
	while n % 2 == 0:
		n //= 2
		c += 1
	return c

def seive(n):
	primes = [True] * (n + 1)
	primes[1] = primes[0] = False
	i = 2
	while i * i <= n:
		if primes[i] == True:
			for j in range(i * i, n + 1, i):
				primes[j] = False
		i += 1
	pr = []
	for i in range(0, n + 1):
		if primes[i]:
			pr.append(i)
	return pr

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def denofactinverse(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return pow(fac, m - 2, m)

def numofact(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return fac

def sod(n):
	s = 0
	while n > 0:
		s += n % 10
		n //= 10
	return s
for xyz in range(0, int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = 2 * n - 1
	for i in range(1, n - 1):
		if l[i - 1] <= l[i] <= l[i + 1] or l[i + 1] <= l[i] <= l[i - 1]:
			continue
		ans += 1
	for i in range(2, n - 1):
		(a, b, c, d) = (l[i - 2], l[i - 1], l[i], l[i + 1])
		if a <= b <= d or d <= b <= a or a <= c <= d or (d <= c <= a) or (a <= b <= c) or (c <= b <= a) or (b <= c <= d) or (d <= c <= b):
			continue
		ans += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))

	def checker(brr):
		m = len(brr)
		for i in range(m):
			for j in range(i + 1, m):
				for k in range(j + 1, m):
					if brr[i] <= brr[j] and brr[j] <= brr[k] or (brr[i] >= brr[j] and brr[j] >= brr[k]):
						return False
		return True
	ans = 0
	for i in range(n):
		brr = []
		for j in range(i, n):
			brr.append(arr[j])
			if len(brr) <= 2:
				ans += 1
				continue
			elif len(brr) >= 5:
				break
			elif checker(brr):
				ans += 1
			else:
				break
	print(ans)


f = lambda x: x == sorted(x) or x[::-1] == sorted(x)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	o = 0
	for i in range(n - 2):
		if not f(a[i:i + 3]):
			o += 1
	for i in range(n - 3):
		if not any((f([a[i + j] for j in range(4) if j != k]) for k in range(4))):
			o += 1
	print(o + n + n - 1)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush, heappop, heapify
from itertools import permutations, combinations
from itertools import accumulate as ac
from random import randint as ri
mod = int(1000000000.0) + 7
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
out = lambda x: stdout.write(str(x) + '\n')

def check(a):
	if len(a) <= 2:
		return False
	value = list(combinations(a, 3))
	f = False
	for cur in value:
		cur = list(cur)
		if cur == sorted(list(cur)) or cur == sorted(list(cur), reverse=True):
			f = True
			break
		if f:
			break
	return f
t = ip()
for _ in range(t):
	n = ip()
	arr = list(inp())
	ans = 0
	k = 5
	for j in range(1, k + 1):
		for i in range(n - j + 1):
			trim = arr[i:i + j]
			f = check(trim)
			if f:
				pass
			else:
				ans += 1
	print(ans)


import sys
from bisect import bisect_left as lb
from collections import deque
from queue import PriorityQueue as pq
from math import *
input_ = lambda : sys.stdin.readline().strip('\r\n')
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
ap = lambda ab, bc, cd: ab[bc].append(cd)
li = lambda : list(input_())
pr = lambda x: print(x)
prinT = lambda x: print(x)
f = lambda : sys.stdout.flush()
inv = lambda x: pow(x, mod - 2, mod)
mod = 10 ** 9 + 7
for _ in range(ii()):
	n = ii()
	a = il()
	ans = 2 * n - 1
	for i in range(n - 2):
		if a[i + 1] > a[i] and a[i + 1] > a[i + 2] or a[i] > a[i + 1] < a[i + 2]:
			ans += 1
	for i in range(n - 3):
		if (a[i + 1] < a[i] < a[i + 2] or a[i + 1] > a[i] > a[i + 2]) and (a[i + 1] < a[i + 3] < a[i + 2] or a[i + 2] < a[i + 3] < a[i + 1]):
			ans += 1
	print(ans)


def check(a, b, c):
	if a <= b <= c or a >= b >= c:
		return False
	else:
		return True
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(n - 2):
		if check(a[i], a[i + 1], a[i + 2]):
			ans += 1
	for i in range(n - 3):
		if check(a[i], a[i + 1], a[i + 2]) and check(a[i], a[i + 1], a[i + 3]) and check(a[i], a[i + 2], a[i + 3]) and check(a[i + 1], a[i + 2], a[i + 3]):
			ans += 1
	print(2 * n - 1 + ans)


import sys
input = sys.stdin.readline

def solve():
	n = int(input())
	arr = list(map(int, input().split()))
	ans = n + n - 1
	for i in range(n - 2):
		if arr[i] == arr[i + 1] or arr[i + 1] == arr[i + 2] or arr[i] <= arr[i + 1] <= arr[i + 2] or (arr[i] >= arr[i + 1] >= arr[i + 2]):
			continue
		ans += 1
		if i < n - 3:
			a4 = arr[i + 3]
			if arr[i + 1] == a4 or arr[i] <= arr[i + 1] <= a4 or arr[i] >= arr[i + 1] >= a4:
				continue
			if arr[i + 2] == a4 or arr[i + 1] <= arr[i + 2] <= a4 or arr[i + 1] >= arr[i + 2] >= a4:
				continue
			if arr[i] <= arr[i + 2] <= a4 or arr[i] >= arr[i + 2] >= a4:
				continue
			ans += 1
	return ans
for _ in range(int(input())):
	print(solve())


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
r = 1
while r <= T:
	n = int(input())
	arr = list(map(int, input().split()))
	ans = 2 * n - 1
	for i in range(n - 2):
		if arr[i] < arr[i + 1] and arr[i] > arr[i + 2]:
			ans += 1
			if i + 3 < n and arr[i + 2] < arr[i + 3] < arr[i + 1]:
				ans += 1
		elif arr[i] > arr[i + 1] and arr[i] < arr[i + 2]:
			ans += 1
			if i + 3 < n and arr[i + 1] < arr[i + 3] < arr[i + 2]:
				ans += 1
		else:
			flag = True
			if arr[i] <= arr[i + 1] <= arr[i + 2]:
				flag = False
			if arr[i] >= arr[i + 1] >= arr[i + 2]:
				flag = False
			if flag:
				ans += 1
	print(ans)
	r += 1


def fun(arr):
	total = 2 * n - 1
	for i in range(n - 2):
		total += (arr[i] - arr[i + 1]) * (arr[i + 1] - arr[i + 2]) < 0
	for i in range(n - 3):
		total += (arr[i + 1] - arr[i + 3]) * (arr[i + 3] - arr[i + 2]) > 0 and (arr[i + 1] - arr[i]) * (arr[i] - arr[i + 2]) > 0
	print(total)
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	fun(arr)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	c = n + max(n - 1, 0) + max(n - 2, 0) + max(n - 3, 0)
	for j in range(n - 2):
		if a[j] <= a[j + 1] and a[j + 1] <= a[j + 2] or (a[j] >= a[j + 1] and a[j + 1] >= a[j + 2]):
			c -= 1
	for j in range(n - 3):
		if a[j] <= a[j + 1] and a[j + 1] <= a[j + 2] or (a[j] >= a[j + 1] and a[j + 1] >= a[j + 2]):
			c -= 1
		elif a[j] <= a[j + 1] and a[j + 1] <= a[j + 3] or (a[j] >= a[j + 1] and a[j + 1] >= a[j + 3]):
			c -= 1
		elif a[j] <= a[j + 2] and a[j + 2] <= a[j + 3] or (a[j] >= a[j + 2] and a[j + 2] >= a[j + 3]):
			c -= 1
		elif a[j + 1] <= a[j + 2] and a[j + 2] <= a[j + 3] or (a[j + 1] >= a[j + 2] and a[j + 2] >= a[j + 3]):
			c -= 1
	print(c)


T = int(input())
for _ in range(T):
	N = int(input())
	A = [int(a) for a in input().split()]
	ans = N + N - 1
	for i in range(N - 2):
		(a, b, c) = (A[i], A[i + 1], A[i + 2])
		if a > b < c or a < b > c:
			ans += 1
	for i in range(N - 3):
		(a, b, c, d) = (A[i], A[i + 1], A[i + 2], A[i + 3])
		if b < a < c and b < d < c or (c < a < b and c < d < b):
			ans += 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	count = n + (n - 1)
	for i in range(n - 2):
		if a[i] < a[i + 1] and a[i + 1] > a[i + 2]:
			count += 1
		if a[i] > a[i + 1] and a[i + 1] < a[i + 2]:
			count += 1
	for i in range(n - 3):
		if a[i + 1] > a[i] > a[i + 2] and a[i + 1] > a[i + 3] > a[i + 2]:
			count += 1
		if a[i + 1] < a[i] < a[i + 2] and a[i + 1] < a[i + 3] < a[i + 2]:
			count += 1
	print(count)


t = int(input())
for p in range(0, t):
	n = int(input())
	l = list(map(int, input().split()))
	s = 2 * n - 1
	for i in range(0, n - 2):
		if l[i + 1] > l[i] and l[i + 1] > l[i + 2] or l[i] > l[i + 1] < l[i + 2]:
			s = s + 1
	for i in range(0, n - 3):
		if (l[i + 1] < l[i] < l[i + 2] or l[i + 1] > l[i] > l[i + 2]) and (l[i + 1] < l[i + 3] < l[i + 2] or l[i + 2] < l[i + 3] < l[i + 1]):
			s = s + 1
	print(s)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	tot = 2 * n - 1
	for i in range(n - 2):
		tot += (arr[i] - arr[i + 1]) * (arr[i + 1] - arr[i + 2]) < 0
	for i in range(n - 3):
		tot += (arr[i + 1] - arr[i + 3]) * (arr[i + 3] - arr[i + 2]) > 0 and (arr[i + 1] - arr[i]) * (arr[i] - arr[i + 2]) > 0
	print(tot)


from collections import *
import os, sys
from io import BytesIO, IOBase
from itertools import combinations

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp = lambda dtype: dtype(input().strip())
inp_d = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [inp(dtype) for _ in range(n)]
inp_2ds = lambda dtype, n: [inp_d(dtype) for _ in range(n)]
inp_enu = lambda dtype: [(i, x) for (i, x) in enumerate(inp_d(dtype))]
inp_enus = lambda dtype, n: [[i, inp_d(dtype)] for i in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
for _ in range(inp(int)):
	(n, a) = (inp(int), inp_d(int))
	good = 2 * n - 1
	for i in range(2, n):
		good += not (a[i - 2] >= a[i - 1] >= a[i] or a[i - 2] <= a[i - 1] <= a[i])
	for i in range(4, n + 1):
		bad = False
		for com in combinations(a[i - 4:i], 3):
			bad |= com[0] >= com[1] >= com[2] or com[0] <= com[1] <= com[2]
		good += 1 - bad
	print(good)


from sys import stdin, stdout
from collections import defaultdict
import math

def get_list():
	return list(map(int, stdin.readline().strip().split()))

def get_int():
	return int(stdin.readline())

def get_ints():
	return map(int, stdin.readline().strip().split())

def get_string():
	return stdin.readline()

def printn(n):
	stdout.write(str(n) + '\n')

def check(a, i, j, k):
	return not (a[i] <= a[j] <= a[k] or a[i] >= a[j] >= a[k])

def solve():
	n = get_int()
	a = get_list()
	ans = 2 * n - 1
	for i in range(n - 2):
		if check(a, i, i + 1, i + 2):
			ans += 1
	for i in range(n - 3):
		if check(a, i, i + 1, i + 2) and check(a, i, i + 2, i + 3) and check(a, i, i + 1, i + 3) and check(a, i + 1, i + 2, i + 3):
			ans += 1
	printn(ans)
t = get_int()
while t:
	t -= 1
	solve()


import math
import sys
input = lambda : sys.stdin.readline().rstrip()

def dist(i, j):
	global a
	return abs(a[i] - a[j]) + abs(i - j)

def check(l, r):
	global a
	for i in range(l, r):
		for j in range(l, r):
			for k in range(l, r):
				if i != j and i != k and (j != k) and (dist(i, j) == dist(i, k) + dist(k, j)):
					return 0
	return 1
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(n):
		ans += sum((check(j, i + 1) for j in range(i, max(i - 9, -1), -1)))
	print(ans)


for _ in range(int(input())):
	onre = 557687
	n = int(input())
	sgrbjhsgdv = 54
	a = list(map(int, input().split()))
	dhbf = 678
	ans = n + n - 1
	gfnfd = 354575
	for i in range(0, n - 2):
		if a[i] <= a[i + 1] <= a[i + 2] or a[i] >= a[i + 1] >= a[i + 2]:
			continue
		ans += 1
		fhdrrdgfb = 67657685
	for i in range(0, n - 3):
		srhgbd = 575465
		if min(a[i], a[i + 2]) <= a[i + 1] <= max(a[i], a[i + 2]):
			continue
		if min(a[i], a[i + 3]) <= a[i + 1] <= max(a[i], a[i + 3]):
			continue
		dhbgfgdtr = 5788687
		if min(a[i], a[i + 3]) <= a[i + 2] <= max(a[i], a[i + 3]):
			continue
		if min(a[i + 1], a[i + 3]) <= a[i + 2] <= max(a[i + 1], a[i + 3]):
			continue
		dthbghtr = 58765876
		ans += 1
	srdhbe = 5545545
	print(ans)


ans = []
for _ in range(int(input())):
	n = int(input())
	u = list(map(int, input().split()))
	cur = 0
	cur += n
	cur += n - 1
	for i in range(2, n):
		if u[i - 2] <= u[i - 1] <= u[i]:
			continue
		if u[i] <= u[i - 1] <= u[i - 2]:
			continue
		cur += 1
	for i in range(3, n):
		s = [u[i - 3], u[i - 2], u[i - 1], u[i]]
		if u[i - 3] == min(s) or u[i] == max(s):
			continue
		if u[i - 3] == max(s) or u[i] == min(s):
			continue
		cur += 1
	ans.append(cur)
print('\n'.join(map(str, ans)))


def check(arr):
	for a in range(len(arr) - 2):
		for b in range(a + 1, len(arr) - 1):
			for c in range(b + 1, len(arr)):
				r1 = arr[b] - arr[a]
				r2 = arr[c] - arr[b]
				if r1 <= 0 and r2 <= 0:
					return True
				if r1 >= 0 and r2 >= 0:
					return True
	return False
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	res = 0
	for right in range(0, n):
		for left in range(max(0, right - 3), right + 1):
			if not check(a[left:right + 1]):
				res += 1
	print(res)


def ok3(a1, a2, a3):
	if (a2 - a1) * (a2 - a3) > 0:
		return 1
	return 0

def ok4(a1, a2, a3, a4):
	if ok3(a1, a2, a3) and ok3(a1, a2, a4) and ok3(a1, a3, a4) and ok3(a2, a3, a4):
		return 1
	return 0
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 2 * n - 1
	for j in range(2, n):
		if ok3(a[j - 2], a[j - 1], a[j]):
			ans += 1
	for j in range(3, n):
		if ok4(a[j - 3], a[j - 2], a[j - 1], a[j]):
			ans += 1
	print(ans)


def dist(x, y, i, j):
	return abs(x - y) + abs(i - j)

def check(a, l, r):
	for i in range(l, r + 1):
		for j in range(l, r + 1):
			for k in range(l, r + 1):
				if i == j or j == k or k == i:
					continue
				elif dist(a[i], a[j], i, j) == dist(a[i], a[k], i, k) + dist(a[j], a[k], j, k):
					return False
	return True

def solve(t_id):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(n):
		for j in range(i, n):
			if check(a, i, j):
				ans += 1
			else:
				break
	print(ans)
t = 1
t = int(input())
for i in range(t):
	solve(i + 1)


from math import ceil, sqrt

def norm(a1, a2, a3):
	if a1 >= a2 and a2 >= a3 or (a1 <= a2 and a2 <= a3):
		return False
	return True
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	cnt = n * 2 - 1
	for i in range(n - 2):
		a1 = a[i]
		a2 = a[i + 1]
		a3 = a[i + 2]
		if norm(a1, a2, a3):
			cnt += 1
	for i in range(n - 3):
		a1 = a[i]
		a2 = a[i + 1]
		a3 = a[i + 2]
		a4 = a[i + 3]
		if not norm(a1, a2, a3):
			continue
		if not norm(a1, a2, a4):
			continue
		if not norm(a1, a3, a4):
			continue
		if not norm(a2, a3, a4):
			continue
		cnt += 1
	print(cnt)


def check(a):
	if len(a) == 3:
		if a[0] >= a[1] >= a[2] or a[0] <= a[1] <= a[2]:
			return False
		return True
	else:
		for i in range(4):
			b = []
			for j in range(4):
				if i != j:
					b.append(a[j])
			if check(b) == False:
				return False
		return True

def main():
	for _ in range(int(input())):
		n = int(input())
		arr = list(map(int, input().split()))
		ans = n + n - 1
		for i in range(n - 2):
			if check(arr[i:i + 3]):
				ans += 1
		for i in range(n - 3):
			if check(arr[i:i + 4]):
				ans += 1
		print(ans)
main()


t = int(input())
for case in range(t):
	n = int(input())
	b = [int(x) for x in input().split()]
	threes = 0
	for i in range(2, n):
		if b[i] >= b[i - 1] and b[i - 1] >= b[i - 2] or (b[i] <= b[i - 1] and b[i - 1] <= b[i - 2]):
			pass
		else:
			threes += 1
	fours = 0
	for i in range(3, n):
		if b[i] < b[i - 2] and b[i - 1] < b[i - 3] and (b[i] > b[i - 1]) and (b[i - 2] > b[i - 3]) or (b[i] > b[i - 2] and b[i - 1] > b[i - 3] and (b[i] < b[i - 1]) and (b[i - 2] < b[i - 3])):
			fours += 1
	print(2 * n - 1 + threes + fours)


t = int(input())
for _ in range(0, t):
	n = int(input())
	a = list(map(int, input().split()))
	total = 2 * n - 1
	for i in range(0, n - 2):
		total += (a[i] - a[i + 1]) * (a[i + 1] - a[i + 2]) < 0
	for i in range(0, n - 3):
		total += (a[i + 1] - a[i + 3]) * (a[i + 3] - a[i + 2]) > 0 and (a[i + 1] - a[i]) * (a[i] - a[i + 2]) > 0
	print(total)


from math import *
import sys
input = sys.stdin.readline
sys.setrecursionlimit(3 * 10 ** 5)
global flag

def inp():
	return int(input())

def st():
	return input().rstrip('\n')

def lis():
	return list(map(int, input().split()))

def ma():
	return map(int, input().split())

def check(a, b, c, x, y, z):
	(dx, dy, dz) = (abs(a - b) + abs(x - y), abs(a - c) + abs(x - z), abs(b - c) + abs(y - z))
	if dx == dy + dz or dy == dx + dz or dz == dx + dy:
		return 0
	return 1
t = inp()
while t:
	t -= 1
	n = inp()
	a = lis()
	r = n + n - 1
	for i in range(n - 2):
		(a1, b, c) = (i + 1, i + 2, i + 3)
		(x, y, z) = (a[i], a[i + 1], a[i + 2])
		if check(a1, b, c, x, y, z):
			r += 1
	for i in range(n - 3):
		(a1, b, c, d, x, y, z, z1) = (i + 1, i + 2, i + 3, i + 4, a[i], a[i + 1], a[i + 2], a[i + 3])
		if check(a1, b, c, x, y, z) and check(a1, b, d, x, y, z1) and check(a1, c, d, x, z, z1) and check(b, c, d, y, z, z1):
			r += 1
	for i in range(n - 4):
		(a1, b, c, d, e, x, y, z, z1, z2) = (i + 1, i + 2, i + 3, i + 4, i + 5, a[i], a[i + 1], a[i + 2], a[i + 3], a[i + 4])
		if check(a1, b, c, x, y, z) and check(a1, b, d, x, y, z1) and check(a1, b, e, x, y, z2) and check(a1, c, d, x, z, z1) and check(a1, c, e, x, z, z2) and check(a1, d, e, x, z1, z2) and check(b, c, d, y, z, z1) and check(b, c, e, y, z, z2) and check(b, d, e, y, z1, z2) and check(c, d, e, z, z1, z2):
			r += 1
	print(r)


import sys
input = sys.stdin.readline

def main():

	def good(i, j, k):
		return not (ar[k] >= ar[j] >= ar[i] or ar[k] <= ar[j] <= ar[i])
	t = int(input())
	for _ in range(t):
		n = int(input())
		ar = list(map(int, input().split()))
		ans = 2 * n - 1
		bad = [False] * n
		for i in range(n - 2):
			if good(i, i + 1, i + 2):
				ans += 1
		for i in range(n - 3):
			if good(i, i + 1, i + 2) and good(i, i + 1, i + 3) and good(i, i + 2, i + 3) and good(i + 1, i + 2, i + 3):
				ans += 1
		print(ans)
main()


import sys
import math
from collections import deque, Counter
int1 = lambda x: int(x) - 1
inp = lambda : int(input())
mi = lambda : map(int, input().split())
li = lambda : list(mi())
mi1 = lambda : map(int1, input().split())
li1 = lambda : list(mi1())
mis = lambda : map(str, input().split())
lis = lambda : list(mis())
pr = print
from collections import defaultdict
mod = 10 ** 9 + 7
Mod = 998244353
INF = 10 ** 18
ans = 0

def f(a, b, c):
	x = 1 + abs(b - a)
	y = 1 + abs(c - b)
	z = 2 + abs(c - a)
	if x + y == z:
		return False
	else:
		return True
t = inp()
for _ in range(t):
	n = inp()
	a = li()
	ans = n + n - 1
	for i in range(n - 2):
		if f(a[i], a[i + 1], a[i + 2]):
			ans += 1
	for i in range(n - 3):
		if f(a[i], a[i + 1], a[i + 2]) and f(a[i], a[i + 1], a[i + 3]) and f(a[i], a[i + 2], a[i + 3]) and f(a[i + 1], a[i + 2], a[i + 3]):
			ans += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	zoz = [int(x) for x in input().split()]
	subs1 = subs2 = 0
	if len(zoz) >= 3:
		for i in range(2, n):
			if zoz[i - 2] <= zoz[i - 1] and zoz[i - 1] <= zoz[i] or (zoz[i - 2] >= zoz[i - 1] and zoz[i - 1] >= zoz[i]):
				subs1 += 1
	if len(zoz) >= 4:
		for i in range(3, n):
			if (zoz[i - 2] <= zoz[i - 1] and zoz[i - 1] <= zoz[i] or (zoz[i - 2] >= zoz[i - 1] and zoz[i - 1] >= zoz[i])) or (zoz[i - 3] <= zoz[i - 1] and zoz[i - 1] <= zoz[i] or (zoz[i - 3] >= zoz[i - 1] and zoz[i - 1] >= zoz[i])) or (zoz[i - 3] <= zoz[i - 2] and zoz[i - 2] <= zoz[i] or (zoz[i - 3] >= zoz[i - 2] and zoz[i - 2] >= zoz[i])) or (zoz[i - 3] <= zoz[i - 2] and zoz[i - 2] <= zoz[i - 1] or (zoz[i - 3] >= zoz[i - 2] and zoz[i - 2] >= zoz[i - 1])):
				subs2 += 1
	if len(zoz) == 2:
		print(3)
	elif len(zoz) == 3:
		print(6 - subs1)
	elif len(zoz) == 1:
		print(1)
	elif len(zoz) == 0:
		print(0)
	else:
		print(n + n - 1 + n - 2 - subs1 + n - 3 - subs2)


from collections import defaultdict as df
from collections import deque as dq
import sys
input = lambda : sys.stdin.readline().rstrip()

def check_increase(arr):
	if not arr:
		return 0
	if len(arr) >= 5:
		return 3
	if len(arr) == 4:
		if arr[0] <= arr[1] <= arr[3] or arr[1] <= arr[2] <= arr[3] or arr[0] <= arr[2] <= arr[3]:
			return 3
		else:
			return 2
	elif len(arr) == 3:
		if arr[0] <= arr[1] <= arr[2]:
			return 3
		else:
			return 2
	else:
		return len(arr)

def check_decrease(arr):
	if not arr:
		return 0
	if len(arr) >= 5:
		return 3
	if len(arr) == 4:
		if arr[0] >= arr[1] >= arr[3] or arr[1] >= arr[2] >= arr[3] or arr[0] >= arr[2] >= arr[3]:
			return 3
		else:
			return 2
	elif len(arr) == 3:
		if arr[0] >= arr[1] >= arr[2]:
			return 3
		else:
			return 2
	else:
		return len(arr)
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	if n == 1:
		print(1)
	elif n == 2:
		print(3)
	else:
		end = 0
		ans = 0
		q = dq()
		while True:
			if end >= n:
				break
			q.append(arr[end])
			res1 = check_increase(q)
			res2 = check_decrease(q)
			end += 1
			if res1 < 3 and res2 < 3:
				ans += len(q)
			else:
				while True:
					q.popleft()
					res1 = check_increase(q)
					res2 = check_decrease(q)
					if res1 < 3 and res2 < 3:
						break
				ans += len(q)
		print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	if n < 3:
		print(2 * n - 1)
	else:
		k = 0
		ans = 2 * n - 1
		for i in range(2, n):
			if arr[i - 2] < arr[i - 1] and arr[i - 1] > arr[i] or (arr[i - 2] > arr[i - 1] and arr[i - 1] < arr[i]):
				ans += 1
				if k == 1 and (not (arr[i - 3] <= arr[i - 2] <= arr[i] or arr[i - 3] >= arr[i - 2] >= arr[i] or arr[i - 3] <= arr[i - 1] <= arr[i] or (arr[i - 3] >= arr[i - 1] >= arr[i]))):
					ans += 1
				else:
					k = 1
			else:
				k = 0
		print(ans)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = n + n - 1
	for i in range(n - 2):
		if arr[i] <= arr[i + 1] and arr[i + 1] <= arr[i + 2] or (arr[i] >= arr[i + 1] and arr[i + 1] >= arr[i + 2]):
			pass
		else:
			ans += 1
	for i in range(n - 3):
		if arr[i] <= arr[i + 1] and arr[i + 1] <= arr[i + 2] or (arr[i] >= arr[i + 1] and arr[i + 1] >= arr[i + 2]):
			pass
		elif arr[i] <= arr[i + 2] and arr[i + 2] <= arr[i + 3] or (arr[i] >= arr[i + 2] and arr[i + 2] >= arr[i + 3]):
			pass
		elif arr[i + 1] <= arr[i + 2] and arr[i + 2] <= arr[i + 3] or (arr[i + 1] >= arr[i + 2] and arr[i + 2] >= arr[i + 3]):
			pass
		elif arr[i] <= arr[i + 1] and arr[i + 1] <= arr[i + 3] or (arr[i] >= arr[i + 1] and arr[i + 1] >= arr[i + 3]):
			pass
		else:
			ans += 1
	print(ans)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 * 10 ** 9, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
for ik in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = 0
	for i in range(n):
		arr = []
		for j in range(min(i + 3, n - 1), i - 1, -1):
			arr = l[i:j + 1]
			f = 1
			for k in range(len(arr)):
				for t in range(k + 1, len(arr)):
					for p in range(t + 1, len(arr)):
						if arr[k] <= arr[t] <= arr[p] or arr[k] >= arr[t] >= arr[p]:
							f = 0
							break
					if f == 0:
						break
				if f == 0:
					break
			if f == 1:
				ans += len(arr)
				break
	print(ans)


import sys
from bisect import bisect
from math import sqrt, ceil, floor

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def rinput():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1000000000.0) + 7

def dist(x, y):
	return abs(x[0] - y[0]) + abs(x[1] - y[1])
for _ in range(iinput()):
	n = iinput()
	a = get_list()
	pts = [[a[i], i + 1] for i in range(n)]
	ans = 2 * n - 1
	for i in range(n - 2):
		if a[i] <= a[i + 1] <= a[i + 2] or a[i] >= a[i + 1] >= a[i + 2]:
			continue
		ans += 1
	for i in range(n - 3):
		l = [a[i], a[i + 1], a[i + 2], a[i + 3]]
		if l[0] <= l[1] <= l[2] or l[0] <= l[1] <= l[3] or l[0] <= l[2] <= l[3] or (l[1] <= l[2] <= l[3]):
			continue
		if l[0] >= l[1] >= l[2] or l[0] >= l[1] >= l[3] or l[0] >= l[2] >= l[3] or (l[1] >= l[2] >= l[3]):
			continue
		ans += 1
	print(ans)


import os, sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd
from _collections import deque
import heapq as hp
from bisect import bisect_left, bisect_right
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 10 ** 9 + 7
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = n + n - 1
	for i in range(0, n - 2):
		if a[i] <= a[i + 1] <= a[i + 2] or a[i] >= a[i + 1] >= a[i + 2]:
			continue
		ans += 1
	for i in range(0, n - 3):
		if min(a[i], a[i + 2]) <= a[i + 1] <= max(a[i], a[i + 2]):
			continue
		if min(a[i], a[i + 3]) <= a[i + 1] <= max(a[i], a[i + 3]):
			continue
		if min(a[i], a[i + 3]) <= a[i + 2] <= max(a[i], a[i + 3]):
			continue
		if min(a[i + 1], a[i + 3]) <= a[i + 2] <= max(a[i + 1], a[i + 3]):
			continue
		ans += 1
	print(ans)


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
from bisect import bisect_left as lower_bound, bisect_right as upper_bound

def so():
	return int(input())

def st():
	return input()

def mj():
	return map(int, input().strip().split(' '))

def msj():
	return map(str, input().strip().split(' '))

def le():
	return list(map(int, input().split()))

def lebe():
	return list(map(int, input()))

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()

def joro(L):
	return ''.join(map(str, L))

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def tr(n):
	return n * (n + 1) // 2

def main():
	import math as my
	for i in range(so()):
		m = so()
		L = le()
		bec = 2 * m - 1
		for i in range(m - 2):
			if L[i + 1] > L[i] and L[i + 1] > L[i + 2]:
				bec += 1
			if L[i] > L[i + 1] and L[i + 2] > L[i + 1]:
				bec += 1
		for i in range(m - 3):
			if L[i] < L[i + 1] and L[i] > L[i + 2] and (L[i + 3] < L[i + 1]) and (L[i + 3] > L[i + 2]):
				bec += 1
			if L[i] > L[i + 1] and L[i + 2] > L[i] and (L[i + 1] < L[i + 3]) and (L[i + 3] < L[i + 2]):
				bec += 1
		print(bec)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys

def triple(a, b, c):
	return b >= a and b <= c or (b >= c and b <= a)
cnt = int(input())
for _ in range(cnt):
	n = int(input())
	nums = list(map(int, input().split()))
	count = n + (n - 1)
	for l in range(n - 2):
		if not triple(nums[l + 0], nums[l + 1], nums[l + 2]):
			count += 1
			if l >= n - 3:
				continue
			if triple(nums[l + 0], nums[l + 1], nums[l + 3]):
				continue
			if triple(nums[l + 0], nums[l + 2], nums[l + 3]):
				continue
			if triple(nums[l + 1], nums[l + 2], nums[l + 3]):
				continue
			count += 1
	print(count)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	i = 2
	j = 0
	goods = n + n - 1
	last_good = False
	while i < len(a):
		if not a[i - 2] <= a[i - 1] <= a[i] and (not a[i - 2] >= a[i - 1] >= a[i]):
			if last_good:
				if not a[i - 3] <= a[i - 2] <= a[i] and (not a[i - 3] >= a[i - 2] >= a[i]) and (not a[i - 3] >= a[i - 1] >= a[i]) and (not a[i - 3] <= a[i - 1] <= a[i]):
					goods += 1
				goods += 1
			else:
				goods += 1
				last_good = True
		else:
			last_good = False
		i += 1
	print(goods)


import math
t = int(input())
for hh in range(0, t):
	n = int(input())
	a = [int(x) for x in input().split()]
	ans = n
	ans += n - 1
	for i in range(0, n - 2):
		val1 = a[i]
		val2 = a[i + 1]
		val3 = a[i + 2]
		if val1 <= val2 and val2 <= val3:
			k = 1
		elif val1 >= val2 and val2 >= val3:
			k = 1
		else:
			ans += 1
	for i in range(0, n - 3):
		val1 = a[i]
		val2 = a[i + 1]
		val3 = a[i + 2]
		val4 = a[i + 3]
		if val1 <= val2 and val2 <= val3:
			k = 1
		elif val1 >= val2 and val2 >= val3:
			k = 1
		elif val2 <= val3 and val3 <= val4:
			k = 1
		elif val2 >= val3 and val3 >= val4:
			k = 1
		elif val1 <= val2 and val2 <= val4:
			k = 1
		elif val1 >= val2 and val2 >= val4:
			k = 1
		elif val1 <= val3 and val3 <= val4:
			k = 1
		elif val1 >= val3 and val3 >= val4:
			k = 1
		else:
			ans += 1
	print(ans)


import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def LI1():
	return list(map(int1, sys.stdin.readline().split()))

def LLI1(rows_number):
	return [LI1() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline().rstrip()
inf = 10 ** 16
md = 10 ** 9 + 7

def solve():
	n = II()
	aa = LI()
	ans = n + n - 1
	for i in range(n - 2):
		if aa[i] <= aa[i + 1] <= aa[i + 2] or aa[i] >= aa[i + 1] >= aa[i + 2]:
			continue
		ans += 1
	for i in range(n - 3):
		mn = min(aa[i], aa[i + 3])
		mx = max(aa[i], aa[i + 3])
		MN = min(aa[i + 1], aa[i + 2])
		MX = max(aa[i + 1], aa[i + 2])
		if MN < mn and MX > mx:
			ans += 1
	print(ans)
for testcase in range(II()):
	solve()


import os
import sys
from io import BytesIO, IOBase

def solve(x):
	for i in range(len(x)):
		for j in range(i + 1, len(x)):
			for k in range(j + 1, len(x)):
				if x[i] >= x[j] >= x[k] or x[i] <= x[j] <= x[k]:
					return 0
	return 1

def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		ans = 2 * n - 1
		for i in range(n - 2):
			ans += solve([a[i], a[i + 1], a[i + 2]])
		for i in range(n - 3):
			ans += solve([a[i], a[i + 1], a[i + 2], a[i + 3]])
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = [int(word) for word in input().split()]
		dp = [1 for i in range(n)]
		for i in range(1, n):
			cur = 1
			up = []
			down = []
			for j in range(i - 1, max(i - 5, -1), -1):
				if a[j] >= a[i]:
					up.append(a[j])
					if len(up) > 2:
						break
					if len(up) == 2 and up[1] >= up[0]:
						break
				if a[j] <= a[i]:
					down.append(a[j])
					if len(down) > 2:
						break
					if len(down) == 2 and down[1] <= down[0]:
						break
				cur += 1
			dp[i] = min(dp[i - 1] + 1, cur)
		print(sum(dp))
main()


def checkIfValidArr(arr):
	if len(arr) <= 2:
		return True
	if len(arr) >= 5:
		return False
	for i in range(len(arr)):
		for j in range(i + 1, len(arr)):
			for k in range(j + 1, len(arr)):
				if arr[i] <= arr[j] and arr[j] <= arr[k] or (arr[i] >= arr[j] and arr[j] >= arr[k]):
					return False
	return True

def findNumGoodArr(arr):
	numGoodArray = 0
	for i in range(len(arr)):
		temp_arr = []
		for j in range(i, len(arr)):
			temp_arr.append(arr[j])
			if checkIfValidArr(temp_arr) is True:
				numGoodArray += 1
			else:
				break
	return numGoodArray
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	print(findNumGoodArr(arr))


PI = 3.141592653589793
INF = float('inf')
MOD = 1000000007

def bin32(num):
	return '{0:032b}'.format(num)

def add(x, y):
	return (x + y) % MOD

def sub(x, y):
	return (x - y + MOD) % MOD

def mul(x, y):
	return x * y % MOD

def gcd(x, y):
	if y == 0:
		return x
	return gcd(y, x % y)

def lcm(x, y):
	return x * y // gcd(x, y)

def power(x, y):
	res = 1
	x %= MOD
	while y != 0:
		if y & 1:
			res = mul(res, x)
		y >>= 1
		x = mul(x, x)
	return res

def mod_inv(n):
	return power(n, MOD - 2)

def prob(p, q):
	return mul(p, power(q, MOD - 2))

def ii():
	return int(input())

def li():
	return [int(i) for i in input().split()]

def ls():
	return [i for i in input().split()]
for t in range(ii()):
	t += 1
	n = ii()
	a = li()
	if n == 1:
		print(1)
		continue
	elif n == 2:
		print(3)
		continue
	ans = 0
	for i in range(n - 3):
		x = a[i:i + 4][:]
		maxi = 4
		if x[0] <= x[1] <= x[2] or x[0] >= x[1] >= x[2]:
			maxi = 2
		elif x[0] <= x[2] <= x[3] or x[0] >= x[2] >= x[3] or x[1] >= x[2] >= x[3] or (x[1] <= x[2] <= x[3]) or (x[0] <= x[1] <= x[3]) or (x[0] >= x[1] >= x[3]):
			maxi = 3
		else:
			maxi = 4
		ans += maxi
	if a[n - 3] <= a[n - 2] <= a[n - 1] or a[n - 3] >= a[n - 2] >= a[n - 1]:
		ans += 2
	else:
		ans += 3
	ans += 3
	print(ans)


import os, sys, math
from io import BytesIO, IOBase
from collections import defaultdict, deque, OrderedDict
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')

def I():
	return int(input())

def In():
	return map(int, input().split())

def ln():
	return list(map(int, input().split()))

def Sn():
	return input().strip()
BUFSIZE = 8192

def find_gt(a, x):
	i = bi.bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return len(a)

def solve():
	n = I()
	l = list(In())
	total = 0
	for i in range(n):
		for j in range(i, n):
			if j - i + 1 >= 5:
				break
			if j - i + 1 <= 2:
				total += 1
				continue
			an = l[i:j + 1]
			ok = True
			for ii in range(len(an)):
				for jj in range(ii + 1, len(an)):
					for kk in range(jj + 1, len(an)):
						if abs(an[kk] - an[jj]) + abs(an[jj] - an[ii]) == abs(an[kk] - an[ii]):
							ok = False
							break
					if not ok:
						break
				if not ok:
					break
			if ok:
				total += 1
	print(total)
	pass

def main():
	T = I()
	for i in range(T):
		solve()
M = 998244353
P = 1000000007

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def fuk(a):
	if a[0] <= a[1] <= a[2]:
		return 1
	if a[0] >= a[1] >= a[2]:
		return 1
	return 0

def fukk(a):
	if a[0] <= a[1] <= a[2]:
		return 1
	if a[1] <= a[2] <= a[3]:
		return 1
	if a[0] <= a[2] <= a[3]:
		return 1
	if a[0] <= a[1] <= a[3]:
		return 1
	if a[0] >= a[1] >= a[2]:
		return 1
	if a[1] >= a[2] >= a[3]:
		return 1
	if a[0] >= a[2] >= a[3]:
		return 1
	if a[0] >= a[1] >= a[3]:
		return 1
	return 0
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = 0
	ll = []
	if n >= 3:
		for i in range(3):
			ll.append(l[i])
		for i in range(3, n):
			if fuk(ll):
				ans += 1
			ll.pop(0)
			ll.append(l[i])
		ans += fuk(ll)
	ll = []
	if n > 3:
		for i in range(4):
			ll.append(l[i])
		for i in range(4, n):
			if fukk(ll):
				ans += 1
			ll.pop(0)
			ll.append(l[i])
		ans += fukk(ll)
	q = 0
	for i in range(n):
		if i <= 3:
			q += n - i
		else:
			break
	print(q - ans)


def naiveSolve():
	return
from itertools import permutations

def main():

	def mDist(i, j):
		return abs(i - j) + abs(a[i] - a[j])
	t = int(input())
	allans = []
	for _ in range(t):
		n = int(input())
		a = readIntArr()
		ans = 2 * n - 1
		for i in range(2, n):
			arr = []
			for j in range(i - 2, i + 1):
				arr.append(j)
			ok = True
			for perm in permutations(arr, 3):
				d1 = mDist(perm[0], perm[1])
				d2 = mDist(perm[1], perm[2])
				d3 = mDist(perm[2], perm[0])
				if d1 + d2 == d3:
					ok = False
			if ok:
				ans += 1
		for i in range(3, n):
			arr = []
			for j in range(i - 3, i + 1):
				arr.append(j)
			ok = True
			for perm in permutations(arr, 3):
				d1 = mDist(perm[0], perm[1])
				d2 = mDist(perm[1], perm[2])
				d3 = mDist(perm[2], perm[0])
				if d1 + d2 == d3:
					ok = False
			if ok:
				ans += 1
		allans.append(ans)
	multiLineArrayPrint(allans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(l, r):
	print('? {} {}'.format(l, r))
	sys.stdout.flush()
	return int(input())

def answerInteractive(x):
	print('! {}'.format(x))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
from math import gcd, floor, ceil
for _abc in range(1):
	main()


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp = lambda : list(map(int, sys.stdin.readline().rstrip('\r\n').split()))
mod = 10 ** 9 + 7
Mod = 998244353
INF = float('inf')
import math
from bisect import *
from heapq import *
from collections import defaultdict as dd
from collections import OrderedDict as odict
from collections import Counter as cc
from collections import deque
from itertools import groupby
sys.setrecursionlimit(20 * 20 * 20 * 20 + 10)

def good(arr):
	n = len(arr)
	for i in range(n):
		for j in range(i + 1, n):
			for k in range(j + 1, n):
				if max(arr[i], arr[k]) >= arr[j] and min(arr[i], arr[k]) <= arr[j]:
					return False
	return True

def solve():
	n = takein()
	arr = takeiar()
	if n == 1:
		print(1)
		return
	if n == 2:
		print(3)
		return
	ans = n + n - 1
	for j in range(0, n - 2):
		if good(arr[j:j + 3]):
			ans += 1
	if n == 3:
		print(ans)
		return
	for j in range(0, n - 3):
		if good(arr[j:j + 4]):
			ans += 1
	print(ans)
	return

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = takein()
	for tt in range(1, t + 1):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

def takein():
	return int(sys.stdin.readline().rstrip('\r\n'))

def takesr():
	return sys.stdin.readline().rstrip('\r\n')

def takeiar():
	return list(map(int, sys.stdin.readline().rstrip('\r\n').split()))

def takesar():
	return list(map(str, sys.stdin.readline().rstrip('\r\n').split()))

def takeivr():
	return map(int, sys.stdin.readline().rstrip('\r\n').split())

def takesvr():
	return map(str, sys.stdin.readline().rstrip('\r\n').split())

def ispalindrome(s):
	return s == s[::-1]

def invert(bit_s):
	temp = int(bit_s, 2)
	inverse_s = temp ^ 2 ** (len(bit_s) + 1) - 1
	rslt = bin(inverse_s)[3:]
	return str(rslt)

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def counter_elements(a):
	q = dict()
	for i in range(len(a)):
		if a[i] not in q:
			q[a[i]] = 0
		q[a[i]] = q[a[i]] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q

def factorial(n, m=1000000007):
	q = 1
	for i in range(n):
		q = q * (i + 1) % m
	return q

def factors(n):
	q = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			q.append(i)
			q.append(n // i)
	return list(sorted(list(set(q))))

def prime_factors(n):
	q = []
	while n % 2 == 0:
		q.append(2)
		n = n // 2
	for i in range(3, int(n ** 0.5) + 1, 2):
		while n % i == 0:
			q.append(i)
			n = n // i
	if n > 2:
		q.append(n)
	return list(sorted(q))

def transpose(a):
	(n, m) = (len(a), len(a[0]))
	b = [[0] * n for i in range(m)]
	for i in range(m):
		for j in range(n):
			b[i][j] = a[j][i]
	return b

def power_two(x):
	return x and (not x & x - 1)

def ceil(a, b):
	return -(-a // b)

def seive(n):
	a = [1]
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p ** 2, n + 1, p):
				prime[i] = False
		p = p + 1
	for p in range(2, n + 1):
		if prime[p]:
			a.append(p)
	return a

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far

def binary_search(li, val):
	ans = -1
	lb = 0
	ub = len(li) - 1
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = mid
			break
	return ans

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	cnt = 0
	for w in range(3, 5):
		for i in range(len(a) - w + 1):
			if w == 3:
				if (a[i + 1] - a[i]) * (a[i + 2] - a[i + 1]) < 0:
					cnt += 1
			elif (a[i + 1] - a[i]) * (a[i + 2] - a[i + 1]) < 0 and (a[i + 1] - a[i]) * (a[i + 3] - a[i + 1]) < 0 and ((a[i + 2] - a[i + 1]) * (a[i + 3] - a[i + 2]) < 0) and ((a[i + 2] - a[i]) * (a[i + 3] - a[i + 2]) < 0):
				cnt += 1
	print(cnt + 2 * len(a) - 1)


import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
input = lambda : sys.stdin.readline().rstrip()
import bisect, string, math, time, functools, random, fractions
from bisect import *
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
from itertools import permutations, combinations, groupby
rep = range
R = range

def I():
	return int(input())

def LI():
	return [int(i) for i in input().split()]

def LI_():
	return [int(i) - 1 for i in input().split()]

def AI():
	return map(int, open(0).read().split())

def S_():
	return input()

def IS():
	return input().split()

def LS():
	return [i for i in input().split()]

def NI(n):
	return [int(input()) for i in range(n)]

def NI_(n):
	return [int(input()) - 1 for i in range(n)]

def NLI(n):
	return [[int(i) for i in input().split()] for i in range(n)]

def NLI_(n):
	return [[int(i) - 1 for i in input().split()] for i in range(n)]

def StoLI():
	return [ord(i) - 97 for i in input()]

def ItoS(n):
	return chr(n + 97)

def LtoS(ls):
	return ''.join([chr(i + 97) for i in ls])

def RLI(n=8, a=1, b=10):
	return [random.randint(a, b) for i in range(n)]

def RI(a=1, b=10):
	return random.randint(a, b)

def INP():
	N = 10
	n = random.randint(1, N)
	a = RLI(n, 1, n)
	return (n, a)

def Rtest(T):
	(case, err) = (0, 0)
	for i in range(T):
		inp = INP()
		a1 = naive(*inp)
		a2 = solve(*inp)
		if a1 != a2:
			print(inp)
			print('naive', a1)
			print('solve', a2)
			err += 1
		case += 1
	print('Tested', case, 'case with', err, 'errors')

def GI(V, E, ls=None, Directed=False, index=1):
	org_inp = []
	g = [[] for i in range(V)]
	FromStdin = True if ls == None else False
	for i in range(E):
		if FromStdin:
			inp = LI()
			org_inp.append(inp)
		else:
			inp = ls[i]
		if len(inp) == 2:
			(a, b) = inp
			c = 1
		else:
			(a, b, c) = inp
		if index == 1:
			a -= 1
			b -= 1
		aa = (a, c)
		bb = (b, c)
		g[a].append(bb)
		if not Directed:
			g[b].append(aa)
	return (g, org_inp)

def GGI(h, w, search=None, replacement_of_found='.', mp_def={'#': 1, '.': 0}, boundary=1):
	mp = [boundary] * (w + 2)
	found = {}
	for i in R(h):
		s = input()
		for char in search:
			if char in s:
				found[char] = (i + 1) * (w + 2) + s.index(char) + 1
				mp_def[char] = mp_def[replacement_of_found]
		mp += [boundary] + [mp_def[j] for j in s] + [boundary]
	mp += [boundary] * (w + 2)
	return (h + 2, w + 2, mp, found)

def TI(n):
	return GI(n, n - 1)

def accum(ls):
	rt = [0]
	for i in ls:
		rt += [rt[-1] + i]
	return rt

def bit_combination(n, base=2):
	rt = []
	for tb in R(base ** n):
		s = [tb // base ** bt % base for bt in R(n)]
		rt += [s]
	return rt

def gcd(x, y):
	if y == 0:
		return x
	if x % y == 0:
		return y
	while x % y != 0:
		(x, y) = (y, x % y)
	return y

def YN(x):
	print(['NO', 'YES'][x])

def Yn(x):
	print('YNeos'[not x::2])

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)

def showf(inp, length=3, end='\n'):
	if show_flg:
		print([' ' * (length - len(str(i))) + str(i) for i in inp], end=end)
mo = 10 ** 9 + 7
inf = float('inf')
FourNb = [(-1, 0), (1, 0), (0, 1), (0, -1)]
EightNb = [(-1, 0), (1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]
compas = dict(zip('WENS', FourNb))
cursol = dict(zip('LRUD', FourNb))
alp = [chr(ord('a') + i) for i in range(26)]

def gcj(c, x):
	print('Case #{0}:'.format(c + 1), x)
show_flg = False
show_flg = True
ans = 0

def check(x):
	if len(x) <= 2:
		return True
	n = len(x)
	for i in range(n - 2):
		for j in range(i + 1, n - 1):
			for k in range(j + 1, n):
				(s, t, u) = (x[i], x[j], x[k])
				if s <= t <= u or s >= t >= u:
					return False
	return True

def naive(n, a):
	ans = 0
	for i in range(n):
		for j in range(i, n):
			if check(a[i:j + 1]):
				ans += 1
	return ans

def solve(n, a):
	ans = 0
	for i in range(n):
		for j in range(i, min(i + 5, n)):
			if check(a[i:j + 1]):
				ans += 1
	return ans
for _ in range(I()):
	n = I()
	a = LI()
	ans = solve(n, a)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	ans = n + n - 1
	for i in range(2, n):
		if a[i - 2] <= a[i - 1] <= a[i]:
			continue
		if a[i - 2] >= a[i - 1] >= a[i]:
			continue
		ans += 1
	for i in range(3, n):
		if a[i - 3] <= a[i - 2] <= a[i - 1]:
			continue
		if a[i - 2] <= a[i - 1] <= a[i]:
			continue
		if a[i - 3] <= a[i - 2] <= a[i]:
			continue
		if a[i - 3] <= a[i - 1] <= a[i]:
			continue
		if a[i - 3] >= a[i - 2] >= a[i - 1]:
			continue
		if a[i - 2] >= a[i - 1] >= a[i]:
			continue
		if a[i - 3] >= a[i - 2] >= a[i]:
			continue
		if a[i - 3] >= a[i - 1] >= a[i]:
			continue
		ans += 1
	print(ans)


import os
import sys
from io import BytesIO, IOBase
import math
from decimal import Decimal
from decimal import *
from collections import defaultdict, deque
import heapq
from decimal import Decimal
getcontext().prec = 25
abcd = 'abcdefghijklmnopqrstuvwxyz'
MOD = 1000000007
BUFSIZE = 8192
from bisect import bisect_left, bisect_right

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split(' ')))
	ans = 2 * n - 1
	for i in range(n - 2):
		if (l[i] - l[i + 1]) * (l[i + 1] - l[i + 2]) < 0:
			ans += 1
	for i in range(n - 3):
		if (l[i] - l[i + 1]) * (l[i] - l[i + 2]) < 0 and (l[i + 2] - l[i + 3]) * (l[i + 1] - l[i + 3]) < 0:
			ans += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	h = []
	(i, j) = (0, 1)
	ans = 1
	while j < n:
		d = []
		if i + 3 < j:
			i += 1
		notgood = True
		while i + 1 < j and notgood:
			notgood = False
			bad = i
			for x in range(i, j + 1):
				for y in range(x + 1, j + 1):
					for z in range(y + 1, j + 1):
						d = sorted([abs(x - y) + abs(a[x] - a[y]), abs(y - z) + abs(a[y] - a[z]), abs(z - x) + abs(a[z] - a[x])])
						if d[0] + d[1] == d[2]:
							notgood = True
							bad = x
			if notgood:
				i = bad + 1
		ans += j - i + 1
		j += 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	ans += n
	ans += n - 1
	for i in range(n - 2):
		if (a[i + 1] - a[i]) * (a[i + 2] - a[i + 1]) < 0:
			ans += 1
	for i in range(n - 3):
		if (a[i + 1] - a[i]) * (a[i + 2] - a[i + 1]) < 0:
			if a[i + 2] < min(a[i], a[i + 1]):
				if a[i + 2] < a[i + 3] < a[i + 1]:
					ans += 1
			elif a[i + 2] > max(a[i], a[i + 1]):
				if a[i + 2] > a[i + 3] > a[i + 1]:
					ans += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	yaxis = list(map(int, input().split()))
	count = 0
	for i in range(n):
		if i - 2 < 0:
			count += i + 1
			continue
		count += 2
		j = i - 1
		k = i - 2
		count += 1
		if yaxis[i] >= yaxis[j] and yaxis[j] >= yaxis[k]:
			count -= 1
			continue
		elif yaxis[i] <= yaxis[j] and yaxis[j] <= yaxis[k]:
			count -= 1
			continue
		if k > 0:
			l = k - 1
			count += 1
			if yaxis[i] >= yaxis[j] and yaxis[j] >= yaxis[l]:
				count -= 1
			elif yaxis[i] >= yaxis[k] and yaxis[k] >= yaxis[l]:
				count -= 1
			elif yaxis[j] >= yaxis[k] and yaxis[k] >= yaxis[l]:
				count -= 1
			elif yaxis[i] <= yaxis[j] and yaxis[j] <= yaxis[l]:
				count -= 1
			elif yaxis[i] <= yaxis[k] and yaxis[k] <= yaxis[l]:
				count -= 1
			elif yaxis[j] <= yaxis[k] and yaxis[k] <= yaxis[l]:
				count -= 1
	print(count)


import sys, math
t = int(input())

def three(x, y, z):
	if x >= y >= z:
		return 0
	elif x <= y <= z:
		return 0
	return 1

def four(x, y, z, w):
	a = three(x, y, z)
	b = three(x, y, w)
	c = three(x, z, w)
	d = three(y, z, w)
	if a == 1 and b == 1 and (c == 1) and (d == 1):
		return 1
	else:
		return 0
while t > 0:
	t -= 1
	n = int(sys.stdin.readline())
	input = sys.stdin.readline()
	a = list(map(int, input.split()))
	ans = 2 * n - 1
	if n <= 2:
		print(ans)
	else:
		for i in range(n - 2):
			ans += three(a[i], a[i + 1], a[i + 2])
		for i in range(n - 3):
			ans += four(a[i], a[i + 1], a[i + 2], a[i + 3])
		print(ans)


import sys
import collections
import math
inf = sys.maxsize

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def input():
	return sys.stdin.readline().strip()
mod = 1000000007

def check(arr):
	if len(arr) <= 2:
		return True
	if len(arr) >= 5:
		return False
	for i in range(len(arr)):
		for j in range(i + 1, len(arr)):
			for k in range(j + 1, len(arr)):
				if arr[i] >= arr[j] >= arr[k] or arr[i] <= arr[j] <= arr[k]:
					return False
	return True
for _ in range(int(input())):
	n = int(input())
	arr = get_array()
	count = 0
	for i in range(n):
		v = []
		for j in range(i, n):
			v.append(arr[j])
			if check(v):
				count += 1
			else:
				break
	print(count)


def o(p1):
	r = len(p1)
	if r < 3:
		return True
	if r >= 5:
		return False
	for i in range(r):
		for k in range(i + 1, r):
			for s in range(k + 1, r):
				if p1[i] <= p1[k] and p1[k] <= p1[s] or (p1[i] >= p1[k] and p1[k] >= p1[s]):
					return False
	return True
z = int(input())
for _ in range(z):
	n = int(input())
	arr = list(map(int, input().split()))
	i = 0
	an = 0
	while i < n:
		y = []
		for j in range(i, n):
			y.append(arr[j])
			if o(y):
				an += 1
			else:
				break
		i += 1
	print(an)


from copy import *
import sys

def init(N, node, A, unit, func):
	n = 1
	while n < N:
		n <<= 1
	for i in range(n * 2 - 1):
		if len(node) <= i:
			node.append(deepcopy(unit))
		else:
			node[i] = deepcopy(unit)
	for i in range(len(A)):
		node[n - 1 + i] = deepcopy(A[i])
	for i in range(n - 2, -1, -1):
		node[i] = func(node[(i << 1) + 1], node[(i << 1) + 2])
	node.append(func)
	node.append(unit)
	node.append(n)

def upd(node, x, a):
	y = node[-1] + x
	node[y - 1] = a
	while y > 1:
		y = y >> 1
		node[y - 1] = node[-3](node[(y << 1) - 1], node[y << 1])

def query(node, l, r):
	(x, y) = (l, r)
	z = node[-1] - 1
	rr = deepcopy(node[-2])
	rl = deepcopy(node[-2])
	while True:
		if x == y:
			return node[-3](rl, rr)
		if x & 1:
			rl = node[-3](rl, node[x + z])
			x += 1
		if y & 1:
			rr = node[-3](node[y + z - 1], rr)
		if z == 0:
			return node[-3](rl, rr)
		x >>= 1
		y >>= 1
		z >>= 1

def bis_min_k(node, k, cond):
	x = k + 1
	while True:
		if node[-1] <= x:
			return x - node[-1]
		if cond(node[(x << 1) - 1]):
			x = x << 1
		else:
			x = (x << 1) + 1

def bis_min(node, l, r, cond):
	(x, y) = (l, r)
	z = node[-1] - 1
	for i in range(30):
		if x + (1 << i) > y:
			break
		if x & 1 << i:
			if cond(node[z + (x >> i)]):
				return bis_min_k(node, z + (x >> i), cond)
			x += 1 << i
		if z == 0:
			break
		z >>= 1
	for i in range(29, -1, -1):
		if i and node[-1] - 1 >> i - 1 == 0:
			continue
		if x + (1 << i) > y:
			continue
		if y - x & 1 << i:
			if cond(node[(node[-1] - 1 >> i) + (x >> i)]):
				return bis_min_k(node, (node[-1] - 1 >> i) + (x >> i), cond)
			x += 1 << i
	return node[-1]
input = sys.stdin.buffer.readline
INF = 10 ** 9 + 7
for t in range(int(input())):
	sega = []
	segb = []
	segarev = []
	segbrev = []
	N = int(input())
	A = list(map(int, input().split()))
	init(N, sega, A[:], 0, lambda x, y: max(x, y))
	init(N, segb, A[:], INF, lambda x, y: min(x, y))
	init(N, segarev, A[::-1], 0, lambda x, y: max(x, y))
	init(N, segbrev, A[::-1], INF, lambda x, y: min(x, y))
	X = [INF] * N
	for i in range(N):
		ra = bis_min(sega, i + 1, N, lambda x: x >= A[i])
		rb = bis_min(segb, i + 1, N, lambda x: x <= A[i])
		la = N - 1 - bis_min(segarev, N - i, N, lambda x: x >= A[i])
		lb = N - 1 - bis_min(segbrev, N - i, N, lambda x: x <= A[i])
		if 0 <= la < N and 0 <= rb < N:
			X[la] = min(X[la], rb)
		if 0 <= lb < N and 0 <= ra < N:
			X[lb] = min(X[lb], ra)
	seg = []
	init(N, seg, [], INF, lambda x, y: min(x, y))
	l = 0
	ANS = 0
	for r in range(N):
		upd(seg, r, X[r])
		while seg[0] <= r:
			upd(seg, l, INF)
			l += 1
		ANS += r - l + 1
	print(ANS)


def argsort(a):
	(ind, _) = zip(*sorted(enumerate(a), key=lambda x: x[1]))
	return ind

def solve(A):
	out = len(A) * 2 - 1
	for i in range(len(A) - 2):
		ind = argsort(A[i:i + 3])
		if ind in {(0, 2, 1), (1, 2, 0), (2, 0, 1), (1, 0, 2)} and A[i + 1] != A[i] and (A[i + 1] != A[i + 2]):
			out += 1
		else:
			continue
		if A[i] == A[i + 2]:
			continue
		if i < len(A) - 3:
			ind = argsort(A[i:i + 4])
			if ind in {(1, 3, 0, 2), (2, 3, 0, 1), (1, 0, 3, 2), (2, 0, 3, 1)} and A[i + 3] != A[i + 1] and (A[i + 3] != A[i + 2]):
				out += 1
	return out
T = int(input())
for t in range(T):
	input()
	(*A,) = map(int, input().split())
	print(solve(A))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = n + n - 1
	for i in range(1, n - 1):
		a = l[i - 1]
		b = l[i]
		c = l[i + 1]
		if abs(a - b) + abs(b - c) != abs(a - c):
			ans += 1
	for i in range(n - 3):
		a = l[i]
		b = l[i + 1]
		c = l[i + 2]
		d = l[i + 3]
		if abs(a - b) + abs(b - c) != abs(a - c) and abs(a - b) + abs(b - d) != abs(a - d) and (abs(a - c) + abs(d - c) != abs(a - d)) and (abs(b - c) + abs(c - d) != abs(b - d)):
			ans += 1
	print(ans)


import sys, os
from io import BytesIO, IOBase
import math
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
from itertools import permutations
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(stdin, stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def smp():
	return map(str, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return Fals
	return True

def solve(ml):
	n = len(ml)
	for i in range(n - 2):
		for j in range(i + 1, n - 1):
			for k in range(j + 1, n):
				if ml[i] <= ml[j] <= ml[k] or ml[i] >= ml[j] >= ml[k]:
					return False
	return True
for _ in range(iinp()):
	n = iinp()
	A = lmp()
	ans = 2 * n - 1
	for i in range(n - 2):
		if i < n - 3 and solve(A[i:i + 4]):
			ans += 1
		if solve(A[i:i + 3]):
			ans += 1
	print(ans)


def is_good(p, q, r):
	if q > max(p, r) or q < min(p, r):
		return True
	else:
		return False
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	good = n + (n - 1)
	for i in range(0, n - 3, 1):
		bool = is_good(a[i], a[i + 1], a[i + 2]) and is_good(a[i], a[i + 1], a[i + 3]) and is_good(a[i], a[i + 2], a[i + 3]) and is_good(a[i + 1], a[i + 2], a[i + 3])
		if bool:
			good += 1
	for i in range(0, n - 2, 1):
		bool = is_good(a[i], a[i + 1], a[i + 2])
		if bool:
			good += 1
	print(good)


answers = []

def solve(n, arr):
	if n == 1:
		print(1)
		return
	if n == 2:
		print(3)
		return
	ans = 3
	for i in range(n - 3):
		ans += 2
		if arr[i] == arr[i + 1]:
			continue
		if arr[i] > arr[i + 1]:
			if arr[i + 1] >= arr[i + 2]:
				continue
			ans += 1
			if arr[i + 2] <= arr[i]:
				continue
			if arr[i + 2] > arr[i]:
				if arr[i + 3] >= arr[i + 2]:
					continue
				if arr[i + 3] > arr[i + 1]:
					ans += 1
		else:
			if arr[i + 1] <= arr[i + 2]:
				continue
			ans += 1
			if arr[i + 2] >= arr[i]:
				continue
			if arr[i + 2] < arr[i]:
				if arr[i + 3] <= arr[i + 2]:
					continue
				if arr[i + 3] < arr[i + 1]:
					ans += 1
	f = n - 3
	ans += 2
	one = arr[n - 3]
	sec = arr[n - 2]
	thi = arr[n - 1]
	if one > sec and thi > sec:
		ans += 1
	if one < sec and thi < sec:
		ans += 1
	print(ans)
T = int(input())
while T:
	n = int(input())
	arr = [int(x) for x in input().split()]
	solve(n, arr)
	T -= 1
for ans in answers:
	print(ans)


def is_bad(l):
	for i in range(2):
		for j in range(i + 1, 3):
			for k in range(j + 1, 4):
				if l[i] >= l[j] >= l[k] or l[i] <= l[j] <= l[k]:
					return True
	return False

def solve():
	n = int(input())
	inp = list(map(int, input().split()))
	ans = n + n - 1
	for i in range(n - 2):
		if all((inp[i + x] <= inp[i + x + 1] for x in range(2))) or all((inp[i + x] >= inp[i + x + 1] for x in range(2))):
			pass
		else:
			ans += 1
	for i in range(n - 3):
		if is_bad(inp[i:i + 4]):
			pass
		else:
			ans += 1
	print(ans)
tests = int(input())
for _ in range(tests):
	solve()


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = n + n - 1
	f = 0
	for i in range(n - 2):
		if (l[i + 1] - l[i]) * (l[i + 2] - l[i + 1]) < 0:
			ans += 1
	for i in range(n - 3):
		if (l[i + 1] - l[i]) * (l[i + 2] - l[i]) < 0 and (l[i + 3] - l[i + 1]) * (l[i + 3] - l[i + 2]) < 0:
			ans += 1
	print(ans)


t = int(input())
for tests in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	ans = 0
	for i in range(1, n - 1):
		if a[i - 1] >= a[i] and a[i] >= a[i + 1] or (a[i - 1] <= a[i] and a[i] <= a[i + 1]):
			continue
		else:
			ans += 1
	for i in range(n - 3):
		if a[i] >= a[i + 1] and a[i + 1] >= a[i + 3] or (a[i] <= a[i + 1] and a[i + 1] <= a[i + 3]) or (a[i] >= a[i + 1] and a[i + 1] >= a[i + 2]) or (a[i] <= a[i + 1] and a[i + 1] <= a[i + 2]) or (a[i + 1] >= a[i + 2] and a[i + 2] >= a[i + 3]) or (a[i + 1] <= a[i + 2] and a[i + 2] <= a[i + 3]) or (a[i] >= a[i + 2] and a[i + 2] >= a[i + 3]) or (a[i] <= a[i + 2] and a[i + 2] <= a[i + 3]):
			continue
		else:
			ans += 1
	ans += n + (n - 1)
	print(ans)


n_tests = int(input())

def is_good(array):
	l = len(array)
	for i in range(l):
		for j in range(i + 1, l):
			for k in range(j + 1, l):
				if array[k] >= array[j] and array[j] >= array[i] or (array[k] <= array[j] and array[j] <= array[i]):
					return False
	return True

def process():
	n = int(input())
	vals = list(map(int, input().split()))
	ans = n + n - 1
	for i in range(n):
		for j in range(i + 2, n):
			if not is_good(vals[i:j + 1]):
				break
			ans += 1
	print(ans)
for i in range(n_tests):
	process()


t = int(input())
for i in range(t):
	n = int(input())
	arr = [int(i) for i in input().split()]
	counter = 2 * n - 1
	i = 3
	while i < n:
		(a, b, c, d) = arr[i - 3:i + 1]
		if b > d >= a > c or c > d >= a > b or c > a >= d > b or (c < d <= a < b):
			counter += 1
		i += 1
	i = 2
	while i < n:
		(a, b, c) = arr[i - 2:i + 1]
		if a < b > c or a > b < c:
			counter += 1
		i += 1
	print(counter)


import math
import os
import sys
from sys import *
from decimal import *
from io import BytesIO, IOBase
from itertools import accumulate, combinations, permutations, combinations_with_replacement, product
from collections import *
M = 10 ** 9 + 7
import heapq
from bisect import *
from functools import lru_cache
from queue import PriorityQueue
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def inpu():
	return int(inp())

def luckynumber(x, n, a):
	if x > 0:
		a.append(x)
	if x > 10 ** 9:
		return a
	elif x < 1000000000000.0:
		luckynumber(x * 10 + 4, n, a)
		luckynumber(x * 10 + 7, n, a)

def lcm(a, b):
	return a * b // math.gcd(a, b)

def query1(l, r):
	if l >= r:
		return -1
	print('?', l + 1, r + 1)
	sys.stdout.flush()
	return int(input()) - 1

def answer(p):
	print('!', p + 1)
	sys.stdout.flush()
	exit()

def rse(arr, n):
	stack = []
	ans = []
	for i in range(n - 1, -1, -1):
		if len(stack) == 0:
			ans.append(n)
		else:
			while len(stack) != 0:
				if stack[-1][0] >= arr[i]:
					stack.pop()
				else:
					break
			if len(stack) == 0:
				ans.append(n)
			else:
				ans.append(stack[-1][1])
		stack.append([arr[i], i])
	ans.reverse()
	return ans

def lse(arr, n):
	stack = []
	ans = []
	for i in range(n):
		if len(stack) == 0:
			ans.append(-1)
		else:
			while len(stack) != 0:
				if stack[-1][0] >= arr[i]:
					stack.pop()
				else:
					break
			if len(stack) == 0:
				ans.append(-1)
			else:
				ans.append(stack[-1][1])
		stack.append([arr[i], i])
	return ans

def mah(arr):
	max1 = 0
	p = rse(arr, len(arr))
	q = lse(arr, len(arr))
	for i in range(len(arr)):
		a = (p[i] - q[i] - 1) * arr[i]
		max1 = max(a, max1)
	return max1

def maxSumIS(arr, n):
	msis = arr.copy()
	for i in range(1, n):
		for j in range(i):
			if arr[i] > arr[j] and msis[i] < msis[j] + arr[i]:
				msis[i] = msis[j] + arr[i]
	c = max(msis)
	p = 5
	return c

def binarysearch2(arr, target):
	lo = 0
	hi = len(arr) - 1
	while lo <= hi:
		mid = (lo + hi) // 2
		if arr[mid] == target:
			if mid != len(arr) - 1:
				if arr[mid + 1] != target:
					return mid
				else:
					lo += 1
			else:
				return mid
			continue
		if arr[mid] > target:
			hi = mid - 1
		else:
			lo = mid + 1

def ngr(arr, n):
	stack = []
	ans = []
	for i in range(n - 1, -1, -1):
		if len(stack) == 0:
			ans.append(-1)
		else:
			while len(stack) > 0:
				if stack[-1][0] < arr[i]:
					stack.pop()
				else:
					break
			if len(stack) == 0:
				ans.append(-1)
			else:
				ans.append(stack[-1][1])
		stack.append([arr[i], i])
	ans.reverse()
	return ans

def alperm(nums, path, result):
	if not nums:
		result.add(tuple(path))
		return
	for i in range(0, len(nums)):
		alperm(nums[:i] + nums[i + 1:], path + [nums[i]], result)
	return result

def minsum(arr, n, m, res, l):
	if n == 1 and m == 1:
		res += arr[0][0]
		l.append(res)
	else:
		if n != 1:
			p = res + arr[n - 1][m - 1]
			minsum(arr, n - 1, m, p, l)
		if m != 1:
			p = res + arr[n - 1][m - 1]
			minsum(arr, n, m - 1, p, l)
	return min(l)

def subset(arr, n, ans, c):
	if n == 0:
		print(c)
		ans.add(tuple(sorted(c)))
		return
	else:
		op = c + [arr[n - 1]]
		subset(arr, n - 1, ans, op)
		subset(arr, n - 1, ans, c)

def catalan(n):
	if n == 0 or n == 1:
		return 1
	catalan = [0] * (n + 1)
	catalan[0] = 1
	catalan[1] = 1
	for i in range(2, n + 1):
		for j in range(i):
			catalan[i] += catalan[j] * catalan[i - j - 1]
	return catalan[n]

def isP(p, i, j):
	if j <= i:
		return True
	if p[i] != p[j]:
		return False
	return isP(p, i + 1, j - 1)

def main():
	t = 1
	t = inpu()
	for _ in range(t):
		n = inpu()
		a = lis()
		ans = 2 * n - 1
		for i in range(1, n - 1):
			if not (a[i - 1] <= a[i] <= a[i + 1] or a[i - 1] >= a[i] >= a[i + 1]):
				ans += 1
		for i in range(1, n - 2):
			(g, h, j, k) = (a[i - 1], a[i], a[i + 1], a[i + 2])
			if not (g <= h <= j or g <= h <= k or g <= j <= k or (h <= j <= k) or (g >= h >= j) or (g >= h >= k) or (g >= j >= k) or (h >= j >= k)):
				ans += 1
		print(ans)
main()


from sys import stdin

def A():
	t = int(stdin.readline())
	while t:
		t -= 1
		s = int(stdin.readline())
		cnt = []
		res = 1
		cnt.append(1)
		while s > res:
			s -= res
			res += 2
			if s < res:
				cnt.append(s)
			else:
				cnt.append(res)
		print(len(cnt))

def B():
	t = int(stdin.readline())
	while t:
		t -= 1
		s1 = [int(x) for x in stdin.readline().split()]
		(n, a, b) = (s1[0], s1[1], s1[2])
		s = stdin.readline()
		cnt = 0
		res = 0
		for i in range(0, len(s)):
			if i == len(s) - 1:
				if s[i] == '0':
					res += a * (cnt + 1) + b
				break
			if s[i] == s[i + 1] == '0':
				cnt += 1
			else:
				if s[i] == '0':
					res += a * (cnt + 1) + b
				cnt = 0
		cnt_1 = 0
		for i in s:
			if i == '1':
				cnt_1 += 1
		if cnt_1 > 0:
			res += a * cnt_1 + b
		res1 = 0
		cnt = 0
		for i in range(0, len(s)):
			if i == len(s) - 1:
				if s[i] == '1':
					res1 += a * (cnt + 1) + b
				break
			if s[i] == s[i + 1] == '1':
				cnt += 1
			else:
				if s[i] == '1':
					res1 += a * (cnt + 1) + b
				cnt = 0
		cnt_1 = 0
		for i in s:
			if i == '0':
				cnt_1 += 1
		if cnt_1 > 0:
			res1 += a * cnt_1 + b
		print(max(res, n * (a + b), res1))

def count(a):
	n = len(a)
	for j in range(0, n):
		for k in range(j + 1, n):
			for k1 in range(k + 1, n):
				if min(a[j], a[k1]) <= a[k] <= max(a[j], a[k1]):
					return False
	return True

def C():
	t = int(stdin.readline())
	while t:
		t -= 1
		n = int(stdin.readline())
		a = [int(x) for x in stdin.readline().split()]
		res = 0
		for i in range(1, 5):
			for j in range(0, n - i + 1):
				res += count(a[j:j + i])
		print(res)
C()


from sys import *
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = 2 * n - 1
	for i in range(n - 2):
		(a, b, c) = l[i:i + 3]
		if a > b < c or a < b > c:
			ans += 1
		if i < n - 3:
			d = l[i + 3]
			if b < a < c and b < d < c or (c < a < b and c < d < b):
				ans += 1
	print(ans)


import sys
import math
from collections import deque
from bisect import bisect_left, bisect_right
I = sys.stdin.readline
II = lambda : int(I())
IN = lambda x: map(int, x.split())
FN = lambda x: map(float, x.split())
L = lambda x: list(IN(x))
M = 1000000007
P = print
T = True
F = False

def find(a, b, c, d):
	if c > b and c > d:
		if b >= d:
			return False
		if a < c and a > b:
			return True
		else:
			return False
	elif c < b and c < d:
		if b <= d:
			return False
		if a > c and a < b:
			return True
		return False
	return False
for _ in range(II()):
	n = II()
	a = L(I())
	s = 2 * n - 1
	if n < 3:
		P(s)
		continue
	s += 1
	if a[0] <= a[1] <= a[2] or a[0] >= a[1] >= a[2]:
		s -= 1
	for i in range(3, n):
		if a[i] >= a[i - 1] >= a[i - 2] or a[i] <= a[i - 1] <= a[i - 2]:
			continue
		elif find(a[i - 3], a[i - 2], a[i - 1], a[i]):
			s += 2
		else:
			s += 1
	P(s)


import math
t = int(input())

def check(x1, y1, x2, y2, x3, y3):
	t1 = abs(x1 - x2) + abs(y1 - y2)
	t2 = abs(x2 - x3) + abs(y2 - y3)
	t3 = abs(x1 - x3) + abs(y1 - y3)
	if t1 + t2 == t3 or t2 + t3 == t1 or t1 + t3 == t2:
		return False
	return True
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().rstrip().split()))
	count = n + n - 1
	for i in range(n - 2):
		if check(arr[i], i, arr[i + 1], i + 1, arr[i + 2], i + 2):
			count += 1
	for i in range(n - 3):
		if check(arr[i], i, arr[i + 1], i + 1, arr[i + 2], i + 2):
			if check(arr[i], i, arr[i + 1], i + 1, arr[i + 3], i + 3):
				if check(arr[i], i, arr[i + 3], i + 3, arr[i + 2], i + 2):
					if check(arr[i + 3], i + 3, arr[i + 1], i + 1, arr[i + 2], i + 2):
						count += 1
	print(count)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def f(p1, p2, p3):
	l2 = [p1, p2, p3]
	l2.sort()
	if len(set([p1[0], p2[0], p3[0]])) > 1:
		if l2[1][0] == l2[2][0]:
			if l2[1][1] < l2[0][1] < l2[2][1]:
				return True
			else:
				return False
		if l2[0][0] == l2[1][0]:
			if l2[0][1] < l2[2][1] < l2[1][1]:
				return True
			else:
				return False
		a = min(l2[0][1], l2[2][1])
		b = max(l2[0][1], l2[2][1])
		if not a <= l2[1][1] <= b:
			return True
	return False
for t in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = 2 * n - 1
	for i in range(n - 2):
		if f([l[i], i], [l[i + 1], i + 1], [l[i + 2], i + 2]):
			ans += 1
	for i in range(n - 3):
		p1 = [l[i], i]
		p2 = [l[i + 1], i + 1]
		p3 = [l[i + 2], i + 2]
		p4 = [l[i + 3], i + 3]
		if f(p1, p2, p3) and f(p1, p3, p4) and f(p1, p2, p4) and f(p2, p3, p4):
			ans += 1
	print(ans)


def ok(b):
	if len(b) <= 2:
		return True
	n = len(b)
	for i in range(n):
		for j in range(i + 1, n):
			for k in range(j + 1, n):
				if b[i] >= b[j] >= b[k] or b[i] <= b[j] <= b[k]:
					return False
	return True

def findCount():
	n = int(input())
	nums = list(map(int, input().split()))
	groups = []
	ans = 0
	for i in range(n):
		b = []
		for j in range(i, n):
			b.append(nums[j])
			if ok(b):
				ans += 1
			else:
				break
	print(ans)

def findSubarrays():
	t = int(input())
	for k in range(t):
		findCount()
findSubarrays()


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	if n == 1:
		print(1)
		continue
	if n == 2:
		print(3)
		continue
	ANS = 3
	for i in range(n - 2):
		if A[i] <= A[i + 1] <= A[i + 2] or A[i] >= A[i + 1] >= A[i + 2]:
			ANS += 2
			continue
		if i == n - 3:
			ANS += 3
			continue
		if A[i] <= A[i + 1] <= A[i + 3] or A[i] >= A[i + 1] >= A[i + 3] or A[i] <= A[i + 2] <= A[i + 3] or (A[i] >= A[i + 2] >= A[i + 3]) or (A[i + 1] <= A[i + 2] <= A[i + 3]) or (A[i + 1] >= A[i + 2] >= A[i + 3]):
			ANS += 3
			continue
		ANS += 4
	print(ANS)


def is_triplet(a, b, c):
	if a <= b and b <= c:
		return True
	if a >= b and b >= c:
		return True
	return False
T = int(input())
for t in range(T):
	n = int(input())
	arr = list(map(int, input().split()))
	ct = n + n - 1
	for i in range(n - 2):
		if is_triplet(arr[i], arr[i + 1], arr[i + 2]):
			continue
		ct += 1
	for i in range(n - 3):
		if is_triplet(arr[i], arr[i + 1], arr[i + 3]) or is_triplet(arr[i], arr[i + 2], arr[i + 3]) or is_triplet(arr[i + 1], arr[i + 2], arr[i + 3]) or is_triplet(arr[i], arr[i + 1], arr[i + 2]):
			continue
		ct += 1
	print(ct)


def solve(a):
	result = 2 * len(a) - 1
	for i in range(len(a) - 2):
		if not check(a[i:i + 3]):
			result += 1
	for i in range(len(a) - 3):
		if not check(a[i:i + 4]):
			result += 1
	return result

def check(a):
	(first, second) = (0, 0)
	first_result = False
	for el in a:
		if el > first:
			first = el
		elif el > second:
			second = el
		else:
			first_result = True
			break
	(first, second) = (2 ** 32, 2 ** 32)
	second_result = False
	for el in a:
		if el < first:
			first = el
		elif el < second:
			second = el
		else:
			second_result = True
			break
	return first_result or second_result
for _ in range(int(input())):
	n = int(input())
	x = [int(x) for x in input().split()]
	print(solve(x))


import math
num_cases = int(input())

def last_idx(array, curr_idx):
	dp_lower = [0 for _ in range(10)]
	dp_higher = [0 for _ in range(10)]
	for i in range(curr_idx - 1, -1, -1):
		for j in range(curr_idx, i, -1):
			if array[i] <= array[j]:
				dp_lower[curr_idx - i] = max(dp_lower[curr_idx - i], dp_lower[curr_idx - j] + 1)
			if array[i] >= array[j]:
				dp_higher[curr_idx - i] = max(dp_higher[curr_idx - i], dp_higher[curr_idx - j] + 1)
			if dp_higher[curr_idx - i] == 2 or dp_lower[curr_idx - i] == 2:
				return i + 1
	return 0
for _ in range(num_cases):
	_ = input()
	array = [int(x) for x in input().split(' ')]
	last_point = 0
	cutoff = 0
	ans = 0
	i = 0
	while i < len(array):
		l = last_idx(array, i)
		ans += i - l + 1
		i += 1
	print(ans)


def check(arr):
	ret = True
	for one in range(4):
		for two in range(4):
			for three in range(4):
				if one != two and two != three and (one != three):
					dist = [abs(arr[one][0] - arr[two][0]) + abs(arr[one][1] - arr[two][1]), abs(arr[one][0] - arr[three][0]) + abs(arr[one][1] - arr[three][1]), abs(arr[three][0] - arr[two][0]) + abs(arr[three][1] - arr[two][1])]
					dist.sort()
					if dist[0] + dist[1] == dist[2]:
						ret = False
						break
			if ret == False:
				break
		if ret == False:
			break
	return ret
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 1:
		print(1)
	elif n == 2:
		print(3)
	else:
		ans = n + (n - 1) + (n - 2) + (n - 3)
		for i in range(n - 2):
			dist = [abs(a[i] - a[i + 1]) + 1, abs(a[i + 1] - a[i + 2]) + 1, abs(a[i] - a[i + 2]) + 2]
			dist.sort()
			if dist[0] + dist[1] == dist[2]:
				ans -= 1
		for i in range(n - 3):
			x = [[a[i], i + 1], [a[i + 1], i + 2], [a[i + 2], i + 3], [a[i + 3], i + 4]]
			if check(x) == False:
				ans -= 1
		print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip()

def solve_tc():
	ans = 0
	n = int(input())
	s = list(map(int, input().split()))
	for i in range(n - 2):
		if s[i + 1] < s[i] and s[i + 1] < s[i + 2] or (s[i + 1] > s[i] and s[i + 1] > s[i + 2]):
			ans += 1
			if i != n - 3:
				if s[i + 1] < s[i] and s[i + 1] < s[i + 3]:
					if s[i + 2] > s[i] and s[i + 2] > s[i + 3]:
						ans += 1
				elif s[i + 1] > s[i] and s[i + 1] > s[i + 3]:
					if s[i + 2] < s[i] and s[i + 2] < s[i + 3]:
						ans += 1
	return str(ans + 2 * n - 1)
t = int(input())
while t > 0:
	t -= 1
	sys.stdout.write(solve_tc() + '\n')


import sys, math, os
from math import factorial, inf, gcd, pi, sqrt, ceil
from heapq import *
from functools import *
from itertools import *
from collections import *
sys.setrecursionlimit(10 ** 5)
if os.environ.get('HOME') == '/Users/clarity':
	os.chdir(os.path.dirname(os.path.abspath(__file__)))
	inp = open('C_test.txt', 'r').readline

	def debug(*args):
		print(*args, file=sys.stderr)
else:
	inp = sys.stdin.readline

	def debug(*args):
		pass

def line():
	return list(map(int, inp().rstrip().split()))

def fline():
	return list(map(float, inp().rstrip().split()))

def number():
	return int(inp())

def print_array(l):
	print(' '.join(list(map(str, l))))

def testcase(t):
	for p in range(t):
		solve()

class Cont:
	ans = 0
	len = -1
	trip_dir = None
	quad_range = None

	def __init__(self, arr) -> None:
		self.arr = arr

	def add(self, v):
		debug(v, self.ans, self.trip_dir, self.quad_range)
		if self.quad_range:
			if self.quad_range[0] < v < self.quad_range[1]:
				self.ans += 1
		if self.trip_dir is not None:
			notr = False
			if self.trip_dir and v < self.arr[self.len]:
				self.ans += 1
			elif not self.trip_dir and v > self.arr[self.len]:
				self.ans += 1
			else:
				notr = True
			if notr or min(self.arr[self.len], self.arr[self.len - 1]) <= v <= max(self.arr[self.len], self.arr[self.len - 1]):
				self.quad_range = None
			elif self.arr[self.len - 1] == v:
				self.quad_range = None
			else:
				self.quad_range = [min(self.arr[self.len], v), max(self.arr[self.len], v)]
		if self.len == -1:
			self.ans += 1
		else:
			self.ans += 2
			if v != self.arr[self.len]:
				self.trip_dir = v > self.arr[self.len]
			else:
				self.trip_dir = None
				self.quad_range = None
		self.len += 1

def solve():
	n = number()
	l = line()
	c = Cont(l)
	for ll in l:
		c.add(ll)
	print(c.ans)

def main():
	testcase(number())
main()


def bad_triplet(a, b, c):
	if a <= b and b <= c:
		return True
	if a >= b and b >= c:
		return True
	return False

def solve():
	n = int(input())
	arr = [int(x) for x in input().split()]
	if n < 3:
		return n + n - 1
	good_subarrays = n + n - 1 + n - 2 + n - 3
	for i in range(n - 2):
		if bad_triplet(arr[i], arr[i + 1], arr[i + 2]):
			good_subarrays -= 1
	for i in range(n - 3):
		if bad_triplet(arr[i], arr[i + 1], arr[i + 2]) or bad_triplet(arr[i], arr[i + 1], arr[i + 3]) or bad_triplet(arr[i + 1], arr[i + 2], arr[i + 3]) or bad_triplet(arr[i], arr[i + 2], arr[i + 3]):
			good_subarrays -= 1
	return good_subarrays
for _ in range(int(input())):
	print(solve())


t = int(input())
for _ in range(0, t):
	n = int(input())
	x = list(map(int, input().split()))
	ans = 2 * n - 1
	cnt = 0
	cnn = 0
	for i in range(2, n):
		if x[i - 1] >= min(x[i], x[i - 2]) and x[i - 1] <= max(x[i - 2], x[i]):
			cnn += 1
	for i in range(3, n):
		if x[i - 1] >= min(x[i], x[i - 2]) and x[i - 1] <= max(x[i - 2], x[i]):
			cnt += 1
		elif x[i - 2] >= min(x[i - 1], x[i - 3]) and x[i - 2] <= max(x[i - 3], x[i - 1]):
			cnt += 1
		elif x[i - 1] >= min(x[i], x[i - 3]) and x[i - 1] <= max(x[i - 3], x[i]):
			cnt += 1
		elif x[i - 2] >= min(x[i], x[i - 3]) and x[i - 2] <= max(x[i - 3], x[i]):
			cnt += 1
	if n > 2:
		ans += n - 2 - cnn
	if n > 3:
		ans += n - 3 - cnt
	print(ans)


def calc(l, n):
	for i in range(l, n + 1, 1):
		for j in range(i + 1, n + 1, 1):
			for k in range(j + 1, n + 1, 1):
				if a[i] <= a[j] <= a[k] or a[i] >= a[j] >= a[k]:
					return False
	return True
t = int(input())
for z in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	j = 0
	ans = 0
	for i in range(n):
		while not calc(j, i):
			j += 1
		ans += i - j + 1
	print(ans)


for t in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	(a1, a2, a3, a4) = (0, 0, 0, 0)
	res = 0 if n < 3 else int(not (a[-3] >= a[-2] >= a[-1] or a[-3] <= a[-2] <= a[-1]))
	for i in range(n - 4, -1, -1):
		(a1, a2, a3, a4) = (a[i], a[i + 1], a[i + 2], a[i + 3])
		if not (a1 >= a2 >= a3 or a1 <= a2 <= a3):
			res += 1
		if min(a2, a3) < a4 < max(a2, a3) and min(a2, a3) < a1 < max(a2, a3):
			res += 1
	print(res + 2 * n - 1)


def checktriple(ind, array):
	(a, b, c) = (array[ind], array[ind + 1], array[ind + 2])
	if a >= b and b >= c:
		return False
	elif a <= b and b <= c:
		return False
	return True
t = int(input())
for i in range(t):
	n = int(input())
	array = [int(j) for j in input().split()]
	if n >= 3:
		tri = n - 2
	else:
		tri = 0
	for ind in range(n - 2):
		if checktriple(ind, array) == False:
			tri -= 1
	if n >= 4:
		qua = n - 3
	else:
		qua = 0
	for ind in range(n - 3):
		(a, b, c, d) = (array[ind], array[ind + 1], array[ind + 2], array[ind + 3])
		if checktriple(ind, array) == True and checktriple(ind + 1, array) == True and (checktriple(0, [a, b, d]) == True) and (checktriple(0, [a, c, d]) == True):
			pass
		else:
			qua -= 1
	print(tri + qua + 2 * n - 1)


import sys, heapq, math, bisect
from collections import defaultdict, deque
input = sys.stdin.readline

def find(x, y, p, q):
	return abs(x - p) + abs(y - q)

def check(s):
	n = len(s)
	for i in range(n):
		for j in range(i + 1, n):
			for k in range(j + 1, n):
				if find(s[i], i, s[k], k) == find(s[i], i, s[j], j) + find(s[j], j, s[k], k):
					return 0
	return 1
T = int(input())
for _ in range(T):
	n = int(input())
	A = list(map(int, input().split()))
	ans1 = 0
	for i in range(n):
		for j in range(i, n):
			if check(A[i:j + 1]) == 1:
				ans1 = ans1 + 1
			else:
				break
	print(ans1)


import math
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 2 * n - 1
	for i in range(n - 2):
		if a[i] <= a[i + 1] <= a[i + 2] or a[i] >= a[i + 1] >= a[i + 2]:
			ans += 0
		else:
			ans += 1
	for i in range(n - 3):
		if a[i] <= a[i + 1] <= a[i + 2] or a[i] >= a[i + 1] >= a[i + 2]:
			ans += 0
		elif a[i] <= a[i + 1] <= a[i + 3] or a[i] >= a[i + 1] >= a[i + 3]:
			ans += 0
		elif a[i] <= a[i + 2] <= a[i + 3] or a[i] >= a[i + 2] >= a[i + 3]:
			ans += 0
		elif a[i + 1] <= a[i + 2] <= a[i + 3] or a[i + 1] >= a[i + 2] >= a[i + 3]:
			ans += 0
		else:
			ans += 1
	print(ans)


def check(a, i):
	c = 0
	if abs(a[i] - a[i + 2]) + 2 != abs(a[i] - a[i + 1]) + 1 + abs(a[i + 1] - a[i + 2]) + 1:
		if abs(a[i] - a[i + 3]) + 3 != abs(a[i] - a[i + 1]) + 1 + abs(a[i + 1] - a[i + 3]) + 2:
			if abs(a[i] - a[i + 3]) + 3 != abs(a[i] - a[i + 2]) + 2 + abs(a[i + 2] - a[i + 3]) + 1:
				if abs(a[i + 1] - a[i + 3]) + 2 != abs(a[i + 1] - a[i + 2]) + 1 + abs(a[i + 2] - a[i + 3]) + 1:
					c = c + 1
	return c

def check1(a, i):
	c = 0
	if abs(a[i] - a[i + 2]) + 2 != abs(a[i] - a[i + 1]) + 1 + abs(a[i + 1] - a[i + 2]) + 1:
		c = c + 1
	return c
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(d) for d in input().split()]
	if len(a) == 1:
		print(1)
	elif len(a) == 2:
		print(3)
	elif len(a) == 3:
		if abs(a[0] - a[2]) + 2 != abs(a[1] - a[2]) + 1 + abs(a[0] - a[1]) + 1:
			print(6)
		else:
			print(5)
	else:
		c = n + n - 1
		for i in range(n - 3):
			c = c + check(a, i)
		for i in range(n - 2):
			c = c + check1(a, i)
		print(c)


import sys, os
from math import *
from bisect import *
from heapq import *
from collections import *
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		n = int(input())
		arr = list(MI())
		out = 2 * n - 1

		def check3(i):
			(a, b, c) = (arr[i - 2], arr[i - 1], arr[i])
			if a >= b >= c:
				return 0
			if a <= b <= c:
				return 0
			return 1

		def checkABC(a, b, c):
			if a >= b >= c:
				return 0
			if a <= b <= c:
				return 0
			return 1

		def check4(i):
			(a, b, c, d) = (arr[i - 3], arr[i - 2], arr[i - 1], arr[i])
			if checkABC(a, b, c) and checkABC(a, b, d) and checkABC(a, c, d) and checkABC(b, c, d):
				return 1
			return 0
		if n >= 3:
			out += check3(2)
		for i in range(3, n):
			out += check3(i) + check4(i)
		print(out)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def MI():
	return map(int, input().split())

def outP(var):
	sys.stdout.write(str(var) + '\n')
MOD = 10 ** 9 + 7
mod = 998244353
main()


def calc(a, i):
	if a[i] == a[i + 1]:
		return i + 2
	if a[i + 1] == a[i + 2]:
		return i + 2
	if a[i] == a[i + 2]:
		return i + 3
	if a[i] < a[i + 1] < a[i + 2]:
		return i + 2
	if a[i] > a[i + 1] > a[i + 2]:
		return i + 2
	if a[i] > a[i + 2] > a[i + 1]:
		return i + 3
	if a[i] < a[i + 2] < a[i + 1]:
		return i + 3
	if i + 3 >= len(a):
		return i + 3
	if a[i + 1] < a[i] < a[i + 2]:
		if a[i + 1] < a[i + 3] < a[i + 2]:
			return i + 4
		return i + 3
	if a[i + 1] > a[i] > a[i + 2]:
		if a[i + 2] < a[i + 3] < a[i + 1]:
			return i + 4
		return i + 3

def solve(a):
	d = [len(a)] * len(a)
	for i in range(len(a) - 2):
		d[i] = calc(a, i)
	answer = 0
	for i in range(len(a)):
		answer += d[i] - i
	return answer
for case in range(int(input())):
	input()
	a = list(map(int, input().split()))
	print(solve(a))


from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 2 * n - 1
	for i in range(n - 2):
		if a[i + 1] > a[i] and a[i + 1] > a[i + 2]:
			ans += 1
		if a[i + 1] < a[i] and a[i + 1] < a[i + 2]:
			ans += 1
	for i in range(n - 3):
		if (a[i + 1] > max(a[i], a[i + 2], a[i + 3]) or a[i + 1] < min(a[i], a[i + 3], a[i + 2])) and (a[i + 2] > max(a[i], a[i + 1], a[i + 3]) or a[i + 2] < min(a[i], a[i + 3], a[i + 1])):
			ans += 1
	print(ans)


import sys
import os.path
from collections import *
import math
import bisect
import heapq as hq
from fractions import Fraction
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
t = int(input())
while t:
	t -= 1
	n = int(input())
	arr = [int(x) for x in input().split()]
	sum = n + n - 1
	for i in range(n - 2):
		if arr[i] >= arr[i + 1] and arr[i + 1] >= arr[i + 2] or (arr[i] <= arr[i + 1] and arr[i + 1] <= arr[i + 2]):
			continue
		else:
			sum += 1
			res = 1
			if i == n - 3:
				continue
			l = i + 3
			for j in range(i, l - 1):
				for k in range(j + 1, l):
					if arr[j] >= arr[k] and arr[k] >= arr[l] or (arr[j] <= arr[k] and arr[k] <= arr[l]):
						res = 0
					if res == 0:
						break
				if res == 0:
					break
			sum += res
	print(sum)


import time, bisect

def main():
	t = i_input()
	for tt in range(t):
		n = i_input()
		a = li_input()
		out = 2 * n - 1
		for i in range(n - 2):
			if a[i] >= a[i + 1] >= a[i + 2] or a[i] <= a[i + 1] <= a[i + 2]:
				continue
			out += 1
			if i + 3 == n:
				continue
			if a[i + 1] >= a[i + 2] >= a[i + 3] or a[i + 1] <= a[i + 2] <= a[i + 3]:
				continue
			if a[i] >= a[i + 1] >= a[i + 3] or a[i] <= a[i + 1] <= a[i + 3] or a[i] >= a[i + 2] >= a[i + 3] or (a[i] <= a[i + 2] <= a[i + 3]):
				continue
			out += 1
		print(out)

def i_input():
	return int(input())

def l_input():
	return input().split()

def li_input():
	return list(map(int, l_input()))

def il_input():
	return list(map(int, l_input()))
TT = time.time()
main()


def solve():
	n = int(input())
	a = [int(i) for i in input().split(' ')]
	ans = 2 * n - 1
	for i in range(n - 2):
		if not (a[i] <= a[i + 1] and a[i + 1] <= a[i + 2] or (a[i] >= a[i + 1] and a[i + 1] >= a[i + 2])):
			ans += 1
	for i in range(n - 3):
		extra = 1
		for l in range(i, i + 2):
			for r in range(i + 2, i + 4):
				for mid in range(l + 1, r):
					if a[l] <= a[mid] and a[mid] <= a[r] or (a[l] >= a[mid] and a[mid] >= a[r]):
						extra = 0
		ans += extra
	print(ans)
t = int(input())
while t > 0:
	t -= 1
	solve()


import sys
from math import *
from functools import *
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	i = 1
	c3 = 0
	c1 = n
	c2 = n - 1
	c4 = 0
	while i < n - 1:
		if (a[i] - a[i - 1]) * (a[i + 1] - a[i]) < 0:
			c3 += 1
			if i < n - 2 and (a[i + 2] - a[i + 1]) * (a[i + 1] - a[i]) < 0 and ((a[i + 2] - a[i]) * (a[i] - a[i - 1]) < 0) and ((a[i + 2] - a[i + 1]) * (a[i + 1] - a[i - 1]) < 0):
				c4 += 1
		i += 1
	print(c1 + c2 + c3 + c4)


A = []
t = int(input())

def isg(l, r):
	for i in range(l, r + 1):
		for j in range(i + 1, r + 1):
			for k in range(j + 1, r + 1):
				if A[i] >= A[j] and A[j] >= A[k]:
					return False
				if A[i] <= A[j] and A[j] <= A[k]:
					return False
	return True
for i in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	ans = 0
	j = 0
	for i in range(n):
		while isg(j, i) == False:
			j += 1
		ans += i - j + 1
	print(ans)


def sol_mansub(n, ar):
	res = 0
	for i in range(len(ar)):
		if i >= n - 2:
			l = n - i
			res += l * (l + 1) // 2
			break
		(a, b, c) = ar[i:i + 3]
		if a <= b <= c or a >= b >= c:
			res += 2
			continue
		l = 3
		if i + 3 < n:
			d = ar[i + 3]
			if not (a <= b <= d or a <= c <= d or b <= c <= d or (a >= b >= d) or (a >= c >= d) or (b >= c >= d)):
				l += 1
		res += l
	return res

def main():
	t = int(input())
	for _ in range(t):
		(n,) = [int(x) for x in input().split()]
		ar = [int(x) for x in input().split()]
		print(sol_mansub(n, ar))
main()


import sys, io, os
BUFSIZE = 8192

class FastIO(io.IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = io.BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(io.IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
MOD = 1000000007

def si():
	return input()

def ii():
	return int(input())

def li():
	return list(map(int, input().split()))

def mi():
	return map(int, input().split())

def sout(v):
	print(v, end=' ')

def d2b(n):
	return bin(n).replace('0b', '')

def twod(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def vow():
	return ['a', 'e', 'i', 'o', 'u']

def let():
	return [chr(i) for i in range(97, 123)]

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def ispow2(x):
	return x and (not x & x - 1)

def prime_factors(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return list(factors)

def binary_search(arr, low, high, x):
	if high >= low:
		mid = (high + low) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] > x:
			return binary_search(arr, low, mid - 1, x)
		else:
			return binary_search(arr, mid + 1, high, x)
	else:
		return -1

def sieve(n):
	primes = []
	least_prime_divs = [0] * (n + 1)
	for i in range(2, n + 1):
		if not least_prime_divs[i]:
			least_prime_divs[i] = i
			primes.append(i)
		for p in primes:
			if i * p > n or p > least_prime_divs[i]:
				break
			least_prime_divs[i * p] = p
	return primes

def solve(arr, k):
	l = len(arr)
	for i in range(l):
		for j in range(i + 1, l):
			for k in range(j + 1, l):
				if abs(arr[i] - arr[k]) + abs(k - i) == abs(arr[i] - arr[j]) + abs(j - i) + abs(arr[j] - arr[k]) + abs(j - k):
					return False
	return True
t = ii()
while t:
	t -= 1
	n = ii()
	a = li()
	ans = 2 * n - 1
	for i in range(n - 2):
		if i < n - 3:
			if solve(a[i:i + 4], i):
				ans += 2
			elif solve(a[i:i + 3], i):
				ans += 1
		elif solve(a[i:i + 3], i):
			ans += 1
	print(ans)


def good(a, b, c):
	return not (a <= b <= c or a >= b >= c)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = n + (n - 1)
	for i in range(n - 2):
		if good(a[i], a[i + 1], a[i + 2]):
			ans += 1
			if i < n - 3 and good(a[i], a[i + 1], a[i + 3]) and good(a[i], a[i + 2], a[i + 3]) and good(a[i + 1], a[i + 2], a[i + 3]):
				ans += 1
	print(ans)


import sys
from math import *
import builtins

def print(x, end='\n'):
	sys.stdout.write(str(x) + end)

def get_int():
	return int(input())

def get_list_ints():
	return list(map(int, input().split()))

def get_char_list():
	s = input()
	return list(s[:len(s) - 1])

def get_tuple_ints():
	return tuple(map(int, input().split()))

def print_iterable(p):
	print(' '.join(map(str, p)))

def binary_search(arr, x):
	low = 0
	high = len(arr) - 1
	mid = 0
	while low <= high:
		mid = (high + low) // 2
		if arr[mid] < x:
			low = mid + 1
		elif arr[mid] > x:
			high = mid - 1
		else:
			return mid
	return high

def main():
	t = get_int()
	for q in range(t):
		n = get_int()
		ls = get_list_ints()
		count = 0
		if n == 1:
			count = 1
		elif n == 2:
			count = 3
		elif n == 3:
			if not (ls[0] <= ls[1] <= ls[2] or ls[0] >= ls[1] >= ls[2]):
				count = 6
			else:
				count = 5
		elif n == 4:
			s = ls
			total = 0
			if not (s[1] <= s[2] <= s[3] or s[1] >= s[2] >= s[3]):
				total += 1
			if not (s[0] <= s[1] <= s[2] or s[0] >= s[1] >= s[2]):
				total += 1
			count += total
			if not (s[0] <= s[1] <= s[3] or s[0] >= s[1] >= s[3]):
				total += 1
			if not (s[0] <= s[2] <= s[3] or s[0] >= s[2] >= s[3]):
				total += 1
			if total == 4:
				count += 1
			count += 2 * n - 1
		else:
			for i in range(n - 2):
				s = ls[i:i + 3]
				if not (s[0] <= s[1] <= s[2] or s[0] >= s[1] >= s[2]):
					count += 1
			for i in range(n - 3):
				s = ls[i:i + 4]
				total = 0
				if not (s[1] <= s[2] <= s[3] or s[1] >= s[2] >= s[3]):
					total += 1
				if not (s[0] <= s[1] <= s[2] or s[0] >= s[1] >= s[2]):
					total += 1
				if not (s[0] <= s[1] <= s[3] or s[0] >= s[1] >= s[3]):
					total += 1
				if not (s[0] <= s[2] <= s[3] or s[0] >= s[2] >= s[3]):
					total += 1
				if total == 4:
					count += 1
			count += 2 * n - 1
		print(count)
	pass
main()


def check_if_good(a, b, c):
	if a <= b <= c or a >= b >= c:
		return False
	return True

def solve(n, arr):
	result = 2 * n - 1
	for x in range(n - 2):
		if check_if_good(arr[x], arr[x + 1], arr[x + 2]):
			result += 1
	for x in range(n - 3):
		if check_if_good(arr[x], arr[x + 1], arr[x + 2]) and check_if_good(arr[x], arr[x + 1], arr[x + 3]) and check_if_good(arr[x], arr[x + 2], arr[x + 3]) and check_if_good(arr[x + 1], arr[x + 2], arr[x + 3]):
			result += 1
	print(result)
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	solve(n, arr)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = n + (n - 1)
	for i in range(n):
		if i + 2 < n:
			if arr[i + 1] >= arr[i] and arr[i + 2] >= arr[i + 1] or (arr[i + 1] <= arr[i] and arr[i + 2] <= arr[i + 1]):
				continue
			ans += 1
		if i + 3 < n:
			if arr[i + 2] >= arr[i] and arr[i + 3] >= arr[i + 2] or (arr[i + 2] <= arr[i] and arr[i + 3] <= arr[i + 2]):
				continue
			if arr[i + 1] >= arr[i] and arr[i + 3] >= arr[i + 1] or (arr[i + 1] <= arr[i] and arr[i + 3] <= arr[i + 1]):
				continue
			if arr[i + 2] >= arr[i + 1] and arr[i + 3] >= arr[i + 2] or (arr[i + 2] <= arr[i + 1] and arr[i + 3] <= arr[i + 2]):
				continue
			ans += 1
	print(ans)


def check(a):
	l = len(a)
	if l == 1 or l == 2:
		return True
	elif l > 4:
		return False
	elif l == 3:
		if a[0] <= a[1] and a[1] <= a[2]:
			return False
		elif a[0] >= a[1] and a[1] >= a[2]:
			return False
		else:
			return True
	elif a[1] < a[3] and a[3] < a[2] and (a[1] < a[0]) and (a[0] < a[2]):
		return True
	elif a[1] > a[3] and a[3] > a[2] and (a[1] > a[0]) and (a[0] > a[2]):
		return True
	else:
		return False
t = int(input())
for c in range(0, t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(0, n):
		for j in range(i, n):
			if check(a[i:j + 1]):
				ans += 1
			else:
				break
	print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	ans = n + n - 1
	for i in range(n - 2):
		if (arr[i] - arr[i + 1]) * (arr[i + 1] - arr[i + 2]) < 0:
			ans += 1
	for i in range(n - 3):
		if (arr[i + 1] - arr[i + 3]) * (arr[i + 3] - arr[i + 2]) > 0 and (arr[i + 1] - arr[i]) * (arr[i] - arr[i + 2]) > 0:
			ans += 1
	print(ans)


from sys import maxsize, stdout, stdin, stderr
mod = int(100000000.0)
import sys

def I():
	return int(stdin.readline())

def lint():
	return [int(x) for x in stdin.readline().split()]

def S():
	return input().strip()

def grid(r, c):
	return [lint() for i in range(r)]
from collections import defaultdict, Counter
import math
import heapq
from heapq import heappop, heappush
import bisect
from itertools import groupby

def gcd(a, b):
	while b:
		a %= b
		tmp = a
		a = b
		b = tmp
	return a

def lcm(a, b):
	return a // gcd(a, b) * b

def check_prime(n):
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def Bs(a, x):
	i = 0
	j = 0
	left = 1
	right = x
	flag = False
	while left < right:
		mi = (left + right) // 2
		if a[mi] <= x:
			left = mi + 1
			i += 1
		else:
			right = mi
			j += 1
	if left > 0 and a[left - 1] == x:
		return (i - 1, j)
	else:
		return (-1, -1)

def nCr(n, r):
	return fact(n) // (fact(r) * fact(n - r))

def fact(n):
	res = 1
	for i in range(2, n + 1):
		res = res * i
	return res

def primefactors(n):
	num = 0
	while n % 2 == 0:
		num += 1
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			num += 1
			n = n // i
	if n > 2:
		num += 1
	return num

def ask(a):
	print('? {}'.format(a), flush=True)
	n = I()
	return n

def dfs(i, p):
	(a, tmp) = (0, 0)
	for j in d[i]:
		if j != p:
			a += 1
			tmp += dfs(j, i)
	if a == 0:
		return 0
	return tmp / a + 1

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n // 2
	if n > 2:
		l.append(n)
	return l
t = I()
for _ in range(t):
	n = I()
	s = lint()
	cur = s[0]
	ans = 0
	if n > 2:
		for i in range(n - 2):
			tmp = [s[i], s[i + 1], s[i + 2]]
			if s[i] <= s[i + 1] <= s[i + 2] or s[i] >= s[i + 1] >= s[i + 2]:
				continue
			else:
				ans += 1
				if i + 3 < n:
					if s[i] <= s[i + 1] <= s[i + 3] or s[i] >= s[i + 1] >= s[i + 3] or s[i] <= s[i + 2] <= s[i + 3] or (s[i] >= s[i + 2] >= s[i + 3]) or (s[i + 1] <= s[i + 2] <= s[i + 3]) or (s[i + 1] >= s[i + 2] >= s[i + 3]):
						continue
					else:
						ans += 1
	ans += 2 * n - 1
	print(ans)


import os
import sys
import math
import collections
import functools
import itertools
import heapq
import bisect
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcde'
MOD = 10 ** 9 + 7
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

def INT():
	return int(input())

def STR():
	return input()

def INTs():
	return tuple(map(int, input().split()))

def ARRINT():
	return [int(i) for i in input().split()]

def ARRSTR():
	return [i for i in input().split()]
for _ in range(INT()):
	n = INT()
	a = ARRINT()
	res = n + (n - 1)
	for i in range(n - 2):
		if a[i] <= a[i + 1] <= a[i + 2]:
			pass
		elif a[i] >= a[i + 1] >= a[i + 2]:
			pass
		else:
			res += 1
		if i + 3 < n:
			if a[i] < a[i + 1] and a[i + 2] < a[i] and (a[i + 2] < a[i + 3] < a[i + 1]):
				res += 1
			if a[i + 1] < a[i] and a[i] < a[i + 2] and (a[i + 1] < a[i + 3] < a[i + 2]):
				res += 1
	print(res)


import sys
t = int(input())

def find(lis):
	n = len(lis)
	for a in range(n - 2):
		for b in range(a + 1, n):
			for c in range(b + 1, n):
				if lis[a] <= lis[b] and lis[b] <= lis[c]:
					return False
				if lis[a] >= lis[b] and lis[b] >= lis[c]:
					return False
	return True
for tt in range(t):
	answer = 0
	n = int(sys.stdin.readline())
	sequence = list(map(int, sys.stdin.readline().split()))
	start = 0
	for i in range(min(n, 2)):
		answer += i + 1
	if n >= 3:
		if find(sequence[0:3]):
			answer += 3
		else:
			answer += 2
	for i in range(3, n):
		if find(sequence[i - 3:i + 1]):
			answer += 4
		elif find(sequence[i - 2:i + 1]):
			answer += 3
		else:
			answer += 2
	print(answer)


def d(p1, p2):
	return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	sol = 0
	for i in range(n - 2):
		done = False
		p1 = [a[i + 0], 1]
		p2 = [a[i + 1], 2]
		p3 = [a[i + 2], 3]
		ds = [d(p1, p2), d(p2, p3), d(p1, p3)]
		ds = sorted(ds)
		if ds[2] != ds[1] + ds[0]:
			sol += 1
		if i < n - 3:
			al = a[i:i + 4]
			if a[i + 0] != a[i + 1] and a[i + 0] != a[i + 2] and (a[i + 3] != a[i + 1]) and (a[i + 3] != a[i + 2]):
				if a[i + 1] == min(al) and a[i + 2] == max(al) or (a[i + 1] == max(al) and a[i + 2] == min(al)):
					sol += 1
	print(sol + n - 1 + n)


from itertools import product, combinations
from math import sqrt

def check(arr):
	if len(arr) == 3:
		if not (arr[0] <= arr[1] <= arr[2] or arr[0] >= arr[1] >= arr[2]):
			return True
		return False
	elif len(arr) == 4:
		if check([arr[0], arr[1], arr[2]]) and check([arr[0], arr[1], arr[3]]) and check([arr[0], arr[2], arr[3]]) and check([arr[1], arr[2], arr[3]]):
			return True
		return False
	return False
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	if n == 1:
		print(1)
		continue
	summ = 2 * n - 1
	if n >= 3:
		start = 0
		end = 3
		while end <= n:
			if check(arr[start:end]):
				if end - start == 3:
					summ += 1
					end += 1
				elif end - start == 4:
					summ += 2
					end += 1
					start += 2
			elif end - start == 3:
				end += 1
				start += 1
			elif end - start == 4:
				start += 1
	print(summ)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def main():
	pass

def binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

def isPrime(n):
	if n == 1:
		return False
	else:
		root = int(n ** 0.5)
		root += 1
		for i in range(2, root):
			if n % i == 0:
				return False
		return True

def lts(l):
	s = ''.join(map(str, l))
	return s

def stl(s):
	l = list(s)
	return l

def sq(a, target, arr=[]):
	s = sum(arr)
	if s == target:
		return arr
	if s >= target:
		return
	for i in range(len(a)):
		n = a[i]
		remaining = a[i + 1:]
		ans = sq(remaining, target, arr + [n])
		if ans:
			return ans

def SieveOfEratosthenes(n):
	cnt = 0
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, n + 1):
		if prime[p]:
			cnt += 1
	return cnt

def nCr(n, r):
	f = math.factorial
	return f(n) // f(r) // f(n - r)
mod = int(1000000000.0) + 7
import math

def func(x, y, z):
	if x <= y <= z or x >= y >= z:
		return False
	else:
		return True
for ___ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 2 * n - 1
	for i in range(n - 2):
		if func(a[i], a[i + 1], a[i + 2]):
			ans += 1
	for i in range(n - 3):
		if func(a[i], a[i + 1], a[i + 2]) and func(a[i], a[i + 1], a[i + 3]) and func(a[i], a[i + 2], a[i + 3]) and func(a[i + 1], a[i + 2], a[i + 3]):
			ans += 1
	print(ans)


import sys
t = int(sys.stdin.readline())
while t > 0:
	n = int(sys.stdin.readline())
	a = list(map(int, input().split()))
	c = 2 * n - 1
	if n <= 2:
		print(c)
	else:
		for i in range(n - 2):
			j = i + 1
			k = j + 1
			if a[i] >= a[j] >= a[k] or a[i] <= a[j] <= a[k]:
				c += 0
			else:
				c += 1
		for i in range(n - 3):
			j = i + 1
			k = j + 1
			l = k + 1
			if a[i] >= a[j] >= a[k] or a[i] <= a[j] <= a[k]:
				c += 0
			elif a[j] >= a[k] >= a[l] or a[j] <= a[k] <= a[l]:
				c += 0
			elif a[i] >= a[j] >= a[l] or a[i] <= a[j] <= a[l]:
				c += 0
			elif a[i] >= a[k] >= a[l] or a[i] <= a[k] <= a[l]:
				c += 0
			else:
				c += 1
		print(c)
	t -= 1


import os
import sys
from math import *
from collections import *
from itertools import *
from heapq import *
from bisect import *
from io import BytesIO, IOBase
from typing import overload

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 998244353
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]

def ok(a):
	n = len(a)
	for m in (1, 2):
		(left, right) = (inf, -inf)
		if m - 1 >= 0:
			left = a[m - 1]
		if m - 2 >= 0:
			left = min(left, a[m - 2])
		if m + 1 < n:
			right = a[m + 1]
		if m + 2 < n:
			right = max(right, a[m + 2])
		if left <= a[m] <= right:
			return False
		(left, right) = (-inf, inf)
		if m - 1 >= 0:
			left = a[m - 1]
		if m - 2 >= 0:
			left = max(left, a[m - 2])
		if m + 1 < n:
			right = a[m + 1]
		if m + 2 < n:
			right = min(right, a[m + 2])
		if left >= a[m] >= right:
			return False
	return True
for _ in range(Int()):
	n = Int()
	a = array()
	ans = n + n - 1
	for i in range(n - 2):
		ans += ok(a[i:i + 3])
	for i in range(n - 3):
		ans += ok(a[i:i + 4])
	print(ans)


t = int(input())

def dist(a, b, c, d):
	return abs(a - c) + abs(b - d)

def bad(a, b, c, d, e, f):
	return dist(a, b, c, d) == dist(a, b, e, f) + dist(e, f, c, d) or dist(a, b, e, f) == dist(a, b, c, d) + dist(e, f, c, d) or dist(e, f, c, d) == dist(a, b, e, f) + dist(a, b, c, d)
for i in range(t):
	n = int(input())
	a = []
	a = str(input()).split(' ')
	ans = 0
	for i in range(n):
		j = i
		f = []
		while j < n:
			f.append((int(a[j]), j))
			ok = True
			for ise in range(len(f)):
				for js in range(ise + 1, len(f)):
					for k in range(js + 1, len(f)):
						if bad(f[ise][0], f[ise][1], f[js][0], f[js][1], f[k][0], f[k][1]):
							ok = False
							break
					if not ok:
						break
				if not ok:
					break
			if not ok:
				break
			j += 1
		ans += j - i
	print(ans)