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,ans,d=int(input()),0,{}
s=list(map(int,input().split()))*2#数据输入,s*2实现“一圈”
#处理数据时，从高度最高的山峰开始（若有多个则随机选一个）
#1 2 4 5 3->5 3 1 2 4
#接下来使用栈结构 每个元素入栈，若当前元素值高于栈顶部的值则弹出顶部元素直到不能弹出
#ans+1的情况：1.添加元素(相邻山可相互看见) 2.弹出元素时每弹出1个+1
#ans-1的情况：弹出多个元素时首个元素和当前元素相邻的情况
#遇到连续等高山时，只执行+1 记录起始位置和连续的长度x并存入字典d->下标m:连续长度x，同时x值每更新一次ans=ans+(更新前的)x-1 用于这一串连续山峰内部相互看见的关系
#后续弹出时如果前面位置m在字典的item中，则ans需要根据相关量加上那一段等高山峰的贡献值
#情况有
#1：区间和新位置不相邻，弹出栈顶元素时ans+区间长度x即可
#2：区间和新位置相邻，弹出栈顶元素时ans+区间长度x再-1
maxn,t=0,0#maxn记录最大值，t记录最大值对应的下标
for i in range(len(s)//2):#前半段足够
    if s[i]>=maxn:
        maxn=s[i]
        t=i
s1=s[t:t+len(s)//2]#得到的新序列
stalk=[]#栈，存储s1下标
stalk.append(0)
ans+=1
d[0]=1
for i in range(1,len(s1)):
    wave=0
    while s1[i]>s1[stalk[-1]]:#新加入的山高于栈顶编号对应的山的情况
        if not stalk[-1] in d.items():#栈顶的山峰的附近无等高山峰
          stalk.pop(-1)
          wave+=1
        else:#有等高山峰
          if d[stalk[-1]]+stalk[-1]==i-1:#相邻的情况
              ans+=d[stalk[-1]]-1
          else:#不相邻的情况
              ans+=d[stalk[-1]]
    if s1[i]==s1[stalk[-1]]:#出现连续山峰
        ans+=d[stalk[-1]]-1
        d[stalk[-1]]+=1#不入栈
    else:
        d[i]=1
        stalk.append(i)
    ans+=1
    if wave>1:
        ans+=wave-1
    else:
        ans+=wave
    if stalk[0]==1 and stalk[-1]==len(s1)-1:
        ans-=1
print(min(ans,n*(n-1)//2))
