#!/usr/bin/ python3.8 import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines class SegTree: """ segment tree with point modification and range product access. """ data_unit = 1 << 30 data_f = min def __init__(self, N): self.N = N self.data = [self.data_unit] * (N + N) def build(self, raw_data): data = self.data f = self.data_f N = self.N data[N:] = raw_data[:] for i in range(N - 1, 0, -1): data[i] = f(data[i << 1], data[i << 1 | 1]) def set_val(self, i, x): data = self.data f = self.data_f i += self.N data[i] = x while i > 1: i >>= 1 data[i] = f(data[i << 1], data[i << 1 | 1]) def fold(self, L, R): """ compute for [L, R) """ vL = vR = self.data_unit data = self.data f = self.data_f L += self.N R += self.N while L < R: if L & 1: vL = f(vL, data[L]) L += 1 if R & 1: R -= 1 vR = f(data[R], vR) L >>= 1 R >>= 1 return f(vL, vR) N, *A = map(int, read().split()) def solve(A): # 小・大の順 A = [0] + A + [N + 1] stack = [N + 1] seg = SegTree(len(A)) seg.build(A) next_high = [N + 1] * (N + 2) for n in range(N, -1, -1): x = A[n] while x > A[stack[-1]]: stack.pop() next_high[n] = stack[-1] stack.append(n) dp = [None] * 17 dp[0] = next_high for n in range(1, 17): prev = dp[n - 1] dp[n] = [prev[prev[i]] for i in range(N + 2)] def bin_search(i): a = A[i] R = len(A) - 2 ret = 0 for n in range(16, -1, -1): m = dp[n][i] if m <= R and seg.fold(i + 1, m) >= a: ret += 1 << n i = m return ret return sum(bin_search(i) for i in range(1, N + 1)) print(solve(A) + solve(A[::-1]))