class BIT: def __init__(self, n): self.n = n self.bit = [0]*(self.n+1) # 1-indexed def init(self, init_val): for i, v in enumerate(init_val): self.add(i, v) def add(self, i, x): # i: 0-indexed i += 1 # to 1-indexed while i <= self.n: self.bit[i] += x i += (i & -i) def sum(self, i, j): # return sum of [i, j) # i, j: 0-indexed return self._sum(j) - self._sum(i) def _sum(self, i): # return sum of [0, i) # i: 0-indexed res = 0 while i > 0: res += self.bit[i] i -= i & (-i) return res def lower_bound(self, x): s = 0 pos = 0 depth = self.n.bit_length() v = 1 << depth for i in range(depth, -1, -1): k = pos + v if k <= self.n and s + self.bit[k] < x: s += self.bit[k] pos += v v >>= 1 return pos def __str__(self): # for debug arr = [self.sum(i,i+1) for i in range(self.n)] return str(arr) import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def main(): n = int(input()) A = list(map(int, input().split())) SA = set(A) SA = sorted(list(A)) atoi = {} for i, a in enumerate(SA): atoi[a] = i N = 2*10**5+50 j = 0 bit = BIT(N+1) from collections import defaultdict ans = 0 for i in range(n): while j < n: if i == j: bit.add(atoi[A[j]], 1) j += 1 else: bit.add(atoi[A[j]], 1) M = SA[bit.lower_bound(j-i+1)] m1 = SA[bit.lower_bound(1)] m2 = SA[bit.lower_bound(2)] if M <= m1+m2: j += 1 else: bit.add(atoi[A[j]], -1) break ans += j-i-1 if i == j: j += 1 else: bit.add(atoi[A[i]], -1) print(ans) if __name__ == '__main__': main()