Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by *n* hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.

In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.

An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
The first line of the input data contains an integer number *n* (3 ≤ *n* ≤ 10<sup class="upper-index">6</sup>), *n* — the amount of hills around the capital. The second line contains *n* numbers — heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 10<sup class="upper-index">9</sup>.
n,maxn,maxn_index=int(input()),0,0
s=list(map(int,input().split()))*2
L,R,C=[0]*1000007,[0]*1000007,[0]*1000007#L,R存储编号,C存储数值
#L[i]表示i左侧比第一个比i高(或等)的位置。
#R[i]表示i右侧第一个比i高(或等)的位置。
#C[i]表示从i到R[i]的左开右闭区间内高度等于i的山的数目
for i in range(len(s)//2):
    if s[i]>maxn:
        maxn=s[i]
        maxn_index=i
s_new=s[maxn_index:maxn_index+len(s)//2]#更换为最高山在起点的序列
s_new.append(s_new[0])#末尾加一个元素
j=n-1
while j>=0:
    R[j]=j+1#由于在尾部添加了一座最高山，R[j]一定存在,可能在正右侧
    while R[j]<n and s_new[R[j]]<s_new[j]:#当前山高于右侧山
        R[j]=R[R[j]]#说明当前的山还不够高,需要向右边寻找更高的山
    if R[j]<n and s_new[R[j]]==s_new[j]:#当前山右侧只有与它等高的山了
        C[j]=C[R[j]]+1#区间山数目+1
        R[j]=R[R[j]]#再向右看有没有更高的山
    j-=1
ans=0
for i in range(n):
    ans+=C[i]
    if s_new [i]==s_new [0]:#与最高峰等高
        continue#跳过本轮循环,因为
    L[i]=i-1
    while L[i]>0 and s_new[L[i]]<=s_new[i]:

        L[i]=L[L[i]]#向左边推
    ans+=2
    if L[i]==0 and R[i]==n:
        ans-=1
print(ans)