class SlidingWindowAggretgation: def __init__(self, op) -> None: self.op = op self.front_stack = [] self.back_stack = [] def __len__(self) -> int: return len(self.front_stack) + len(self.back_stack) def __bool__(self) -> bool: return len(self) > 0 def __str__(self) -> str: data = [x for x, _ in self.front_stack][::-1] + [x for x, _ in self.back_stack] return str(data) def append(self, x) -> None: fx = x if self.back_stack: fx = self.op(self.back_stack[-1][1], x) self.back_stack.append((x, fx)) def popleft(self) -> None: if not self.front_stack: x = fx = self.back_stack.pop()[0] self.front_stack.append((x, fx)) while self.back_stack: x = self.back_stack.pop()[0] fx = self.op(x, fx) self.front_stack.append((x, fx)) self.front_stack.pop() def all_prod(self): res = None if self.front_stack: res = self.front_stack[-1][1] if self.back_stack: if res is None: res = self.back_stack[-1][1] else: res = self.op(res, self.back_stack[-1][1]) return res def op(a, b): m11, m12, M1 = a m21, m22, M2 = b if m11 < m21: n1 = m11 n2 = min(m21, m12) else: n1 = m21 n2 = min(m11, m22) return (n1, n2, max(M1, M2)) n = int(input()) a = list(map(int, input().split())) INF = 10 ** 18 ans = 0 SWAG = SlidingWindowAggretgation(op) ans = 0 r = 0 def ok(r): m1, m2, M = SWAG.all_prod() return max(M, a[r]) <= m1 + min(m2, a[r]) for l in range(n): while l == r or (r < n and ok(r)): SWAG.append((a[r], INF, a[r])) r += 1 ans += r - l - 1 SWAG.popleft() print(ans)