import sys readline=sys.stdin.readline import bisect def Cartesian_Tree(lst,maximum=False): N=len(lst) parents=[None]*N stack=[] for i in range(N): prev=None if maximum: while stack and lst[stack[-1]]lst[i]: prev=stack.pop() if prev!=None: parents[prev]=i if stack: parents[i]=stack[-1] stack.append(i) graph=[[] for x in range(N)] for x in range(N): if parents[x]!=None: graph[parents[x]].append(x) else: root=x return graph,root N=int(readline()) P=list(map(int,readline().split())) ans=0 for P in (P,P[::-1]): graph,root=Cartesian_Tree(P,maximum=True) query=[None]*N stack=[(0,root,N)] while stack: l,rt,r=stack.pop() query[rt]=l for x in graph[rt]: if xP[i]: stack.pop() ans+=len(stack)-bisect.bisect_left(stack,query[i]) stack.append(i) print(ans)