```go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
writer := bufio.NewWriter(os.Stdout)
defer writer.Flush()
var t int
if _, err := fmt.Fscan(reader, &t); err != nil {
return
}
for ; t > 0; t-- {
var n int
fmt.Fscan(reader, &n)
a := make([]int, n)
for i := 0; i < n; i++ {
fmt.Fscan(reader, &a[i])
}
ans := 0
for i := 0; i < n; i++ {
// Subarrays of length 1 are always good
ans++
// Subarrays of length 2 are always good
if i+1 < n {
ans++
}
// Subarrays of length 3
if i+2 < n {
if !isBad(a[i], a[i+1], a[i+2]) {
ans++
}
}
// Subarrays of length 4
if i+3 < n {
// A subarray of length 4 is good if no 3 indices form a bad triple.
// We check all 4 combinations of triples.
if !isBad(a[i], a[i+1], a[i+2]) &&
!isBad(a[i+1], a[i+2], a[i+3]) &&
!isBad(a[i], a[i+1], a[i+3]) &&
!isBad(a[i], a[i+2], a[i+3]) {
ans++
}
}
// Subarrays of length >= 5 always contain a monotonic subsequence of length 3
// (Erdos-Szekeres theorem), which constitutes a bad triple.
// So no need to check length >= 5.
}
fmt.Fprintln(writer, ans)
}
}
// isBad returns true if the points corresponding to values x, y, z (with indices i < j < k)
// form a bad triple. This happens if y is metrically between x and z, which for the given
// Manhattan distance definition simplifies to the sequence being monotonic.
func isBad(x, y, z int) bool {
return (x <= y && y <= z) || (x >= y && y >= z)
}
```