#include<bits/stdc++.h>
using namespace std;
const int maxn=2*1e6+10;
int a[maxn],q[maxn],n;
inline int read(){
	int x=0,f=1;char c=getchar();
	while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
	while(c>='0'&&c<='9'){x=(x<<1)+(x<<3)+c-'0';c=getchar();}
	return x*f;
}
int main(){
	n=read();
	for(int i=1;i<=n;i++)
		a[i]=read();
	int l=1,r=0,ans=0,cnt=0;
	for(int i=1;i<=n;i++){
		while(l<=r&&a[i]>a[q[r]])r--,ans++;
		if(r)ans++;
		q[++r]=i;
		//for(int j=l;j<=r;j++)
		//	printf("%d ",q[j]);
		//printf("%d\n",ans);
	}
	cnt=ans;
	for(int i=1;i<=n;i++){
		while(l<=r&&a[i]>a[q[r]])r--,ans++;
		if(r)ans++;
		q[++r]=i;
		//for(int j=l;j<=r;j++)
		//	printf("%d ",q[j]);
		//printf("%d\n",ans);
	}
	printf("%d\n",ans-cnt-2);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define int long long
#define fi first
#define se second
#define mp make_pair
#define bao(a,b,c) mp(mp(a,b),c)
int n;
const int maxn=2e6+100;
int a[maxn],lmost,rmost,maxval;
vector < int > pos[maxn],ve;
//#define isde
void myinit(){
	cin >> n;
	for (int i=1;i<=n;i++){
		cin >> a[i];
		ve.push_back(a[i]);
	}
	sort(ve.begin(),ve.end());
	ve.erase(unique(ve.begin(),ve.end()),ve.end());
	for (int i=1;i<=n;i++){
		a[i]=lower_bound(ve.begin(),ve.end(),a[i])-ve.begin()+1;
	}
	for (int i=1;i<=n;i++){
		a[i+n]=a[i];maxval=max(maxval,max(a[i],a[i+n]));
	}
	for (int i=1;i<=n;i++){
		if (a[i]==maxval){
			lmost=i;break;
		}
	}
	for (int i=n+1;i<=2*n;i++){
		if (a[i]==maxval){
			rmost=i;break;
		}
	}
	for (int i=lmost;i<=rmost;i++) pos[a[i]].push_back(i);
	#ifdef isde
	cout << lmost << ' ' << rmost << ' ' << maxval << endl;
	for (int i=1;i<=maxval;i++){
		cout << i << ':';for (int j=0;j<pos[i].size();j++) cout << pos[i][j] << ' ';cout << endl;
	}
	#endif
}
typedef pair < int,int > pii;
typedef pair < pii,int > piii;
piii dfs(int l,int r,int k){
	int ff,ss,ret=0;
	if (l>r) return bao(0,0,0);
	if (k==1){
		#ifdef isde
		printf("dfs:%d %d %d %d %d %d\n",l,r,k,r-l+1,r-l+1,(r-l+1)*(r-l)/2);
		#endif
		if (k!=maxval) return bao(r-l+1,r-l+1,(r-l+1)*(r-l)/2);
		else return bao(r-l+1,r-l+1,n*(n-1)/2);
	}
	int le=lower_bound(pos[k].begin(),pos[k].end(),l)-pos[k].begin();
	int ri=upper_bound(pos[k].begin(),pos[k].end(),r)-pos[k].begin()-1;
	if (le>ri){
		piii tmp=dfs(l,r,k-1);
		return tmp;
	}
	piii tmp1=dfs(l,pos[k][le]-1,k-1),tmp2=dfs(pos[k][ri]+1,r,k-1);
	ff=tmp1.fi.fi+ri-le+1,ss=tmp2.fi.se+ri-le+1;
	for (int i=le;i<ri;i++){
		piii tmp=dfs(pos[k][i]+1,pos[k][i+1]-1,k-1);
		ret+=tmp.se+tmp.fi.fi+tmp.fi.se;
	}
	ret+=tmp1.fi.se+tmp2.fi.fi+tmp1.se+tmp2.se;
//	cout << ret << endl;
	if (k==maxval) ret+=(pos[k].size()-2)*(pos[k].size()-1)/2;
	else ret+=(ri-le+1)*(ri-le)/2;
	#ifdef isde
	printf("dfs:%d %d %d %d %d %d\n",l,r,k,ff,ss,ret);
	#endif
	return bao(ff,ss,ret);
}
int b[maxn];
int spe_jud(){
	int tmp=pos[maxval][0];
	int maxv=0;
	for (int i=tmp+1;i<pos[maxval][1];i++){
		if (a[i]>=maxv) maxv=a[i],b[i]++;
	}
	maxv=0;
	for (int i=pos[maxval][pos[maxval].size()-1]-1;i>pos[maxval][pos[maxval].size()-2];i--){
		if (a[i]>=maxv) maxv=a[i],b[i]++;
	}
	int sum3=0;
	#ifdef isde
	for (int i=1;i<=n+n;i++) cout << b[i] << ' ';cout << endl;
	#endif
	for (int i=tmp+1;i<tmp+n;i++) sum3+=(b[i]>1?b[i]-1:0);
//	cout << sum1 << ' ' << sum2 << ' ' << sum3 << endl;
	return sum3;
}
signed main(){
// 	freopen("i.in","r",stdin);
// 	freopen("1.out","w",stdout);
	myinit();
	piii ans=dfs(lmost,rmost,maxval);
	int tmp=spe_jud();
	cout << ans.se-tmp << endl;
//	if (pos[maxval].size()==0) cout << ans.se+tmp << endl;
//	else cout << ans.fi.fi+ans.fi.se+ans.se << endl;
	return 0;
}


#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
const int MAXN=1e6+50;
typedef long long ll;
struct mt
{
    ll high,num;
    mt(){high=0;num=1;}
};
ll n,ans,a[MAXN],v[MAXN],imax,pos;
stack<mt> S;
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        imax=max(a[i],imax);
    }
    for(int i=1;i<=n;i++)
        if(a[i]==imax)
        {
            pos=i;
            break;
        }
    int pos2=pos,pos3=pos;
    for(int i=1;i<n;i++)
    {
        if(pos2==n) pos2=0;
        mt x;
        x.high=a[++pos2];
        if(S.empty())   S.push(x);
        else
        {
            if(x.high>=S.top().high)
            {
                if(x.high>=S.top().high)
                {
                while(!S.empty()&&x.high>S.top().high)  ans+=S.top().num,S.pop();
                if(!S.empty()&&x.high==S.top().high)    ans+=S.top().num,S.top().num+=x.num;
                else S.push(x);
                if(S.size()!=1) ans++;
                }
            }
            else S.push(x),ans++;
        }
    }
    int max=0;
    for(int i=1;i<n;i++)
    {
        if(pos3==n) pos3=0;
        int x=a[++pos3];
        if(x>=max)  v[pos3]=1,max=x;
    }
    max=0;
    for(int i=1;i<n;i++)
    {
        if(pos==1)  pos=n+1;
        int x=a[--pos];
        if(x>=max)  v[pos]=1,max=x;
    }
    for(int i=1;i<=n;i++)
        if(v[i])    ans++;
    cout<<ans<<endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxn=2*1e6+10;
int a[maxn],b[maxn],q[maxn],sz[maxn],n;
inline int read(){
	int x=0,f=1;char c=getchar();
	while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
	while(c>='0'&&c<='9'){x=(x<<1)+(x<<3)+c-'0';c=getchar();}
	return x*f;
}
int b1,b2,n1;
signed main(){
	n=read();
	int p=0;
	for(int i=1;i<=n;i++){
		a[i]=read();
		if(a[i]>a[p])p=i;
		if(a[i]>b1)b2=b1,b1=a[i],n1=1;
		else if(a[i]==b1)n1++;
		else if(a[i]>b2)b2=a[i];
	}
	//printf("%d %d %d\n",b1,n1,b2);
	for(int i=1;i<=n;i++)
		b[i]=a[(i+p-1)%n+1];
	//for(int i=1;i<=n;i++)
	//	printf("%d ",b[i]);
	//puts("");
	int l=1,r=0,ans=0;
	for(int i=1;i<=n;i++){
		while(l<=r&&b[i]>b[q[r]])r--,ans++;
		if(r>=l){
			if(b[i]==b[q[r]])ans+=min(r,sz[r]+1);
			else ans++;
		}
		q[++r]=i;
		if(b[i]==b[q[r-1]])sz[r]=sz[r-1]+1;
		else sz[r]=1;
		//printf("%d\n",ans);
	}
	p=0;
	for(int i=1;i<n;i++)
		if(b[i]>=b[p]){
			p=i;
			if(n1>1&&b[p]==b1);
			else if(n1==1&&b[p]==b2);
			else ans++;
		}
	printf("%lld\n",ans);
	return 0;
}


#include <cstdio>
#include <iostream>
using namespace std;
const int MAXX = 10005;

long long a[MAXX] , tf[MAXX] , l[MAXX] , r[MAXX] , cnt[MAXX];
long long n , x , sum;

int main(void ) {
	scanf("%lld",&n);
	for (long long i=0; i<n; i++ ) scanf("%lld",a+i);
	for (long long i=1; i<n; i++ ) {
		if (a[i] > a[x]) {
			x = i;
		}
	}
	for (long long i=0; i<=n; i++ ) {
		tf[i] = a[(i + x) % n];
	}//转环为链操作
	for (long long i=1; i<=n; i++ ) {
		 l[i] = i - 1;//初始化
		 while (l[i] != 0 && tf[i] >= tf[l[i]]) {
		 	l[i] = l[l[i]];//满足条件
		 }
	}
	for (long long i=n-1; i>=0; i-- ) {
		r[i] = i + 1;
		while (r[i] < n && tf[i] > tf[r[i]]) {
			r[i] = r[r[i]];
		}
		if (r[i] < n && tf[i] == tf[r[i]]) {
			cnt[i] = cnt[r[i]] + 1;
			r[i] = r[r[i]];
		}
	}

	for (long long i=0; i<n; i++ ) {
		sum += cnt[i];
		if (tf[i] < tf[0]) {
			sum += 2;
			if (!l[i] && r[i] == n) {
				sum-- ;
			}
		}
	}
	printf("%lld",sum);
}


#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define N 1000005
#define int long long

using namespace std;

int n , a[N] , t[N] , l[N] ,  r[N] , p;

signed main()
{
	cin>>n;
	for (int i=1 ; i<=n ; i++) scanf( "%lld" , t+i ) , p=(t[i]>t[p])?i:p;
	for (int i=0 ; i<=n ; i++) a[i]=t[(i+p)%n];

	memset( t , 0 , sizeof( t ) );
	for (int i=1 ; i<=n ; i++)
	{
		l[i]=i-1;
		while ( l[i] && a[i]>=a[l[i]] ) l[i]=l[l[i]];
	}
	for (int i=n-1 ; i>=0 ; i--)
	{
		r[i]=i+1;
		while ( r[i]!=n && a[i]>a[r[i]] ) r[i]=r[r[i]];

		if ( r[i]!=n && a[i]==a[r[i]] ) t[i]=t[r[i]]+1 , r[i]=r[r[i]];
	}

	int ans=0;
	for (int i=0 ; i<n ; i++)
	{
		ans+=t[i];
		if ( a[i]<a[n] ) ans+=(l[i]==0&&r[i]==n)?1:2;
	}

	cout<<ans<<"\n";

	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define endl "\n"
#define LL long long int
#define vi vector<int>
#define vl vector<LL>
#define all(V) V.begin(),V.end()
#define scs(s) scanf("%s",s)
#define pii pair<int,int>
#define pll pair<LL,LL>
#ifndef ONLINE_JUDGE
#define cout cerr
#endif
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
    cerr << *it << " = " << a << endl;
    err(++it, args...);
}
#define cmax(a,b) ((a) = (a) > (b) ? (a) : (b))
#define cmin(a,b) ((a) = (a) < (b) ? (a) : (b))
#define debug(x)  cerr << #x << " = " << x << endl
function<void(void)> ____ = [](){ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);};
template <typename T> vector<T>& operator << (vector<T> &__container, T x){ __container.push_back(x); return __container; }
template <typename T> ostream& operator << (ostream &out, vector<T> &__container){ for(T _ : __container) out << _ << ' '; return out; }
void sci(){}
template<typename... Args> void sci(int &x, Args&... args){ scanf("%d",&x); sci(args...); }
void scl(){}
template<typename... Args> void scl(LL &x, Args&... args){ scanf("%lld",&x); scl(args...); }
const int MAXN = 1e6+7;
int n, A[MAXN], B[MAXN], l[MAXN], r[MAXN], cnt[MAXN];
int stk[MAXN], top;
void solve(){
    sci(n);
    for(int i = 1; i <= n; i++) sci(A[i]);
    int maxx = *max_element(A+1,A+1+n);
    int p = 0;
    for(int i = 1; i <= n; i++) if(A[i]==maxx){
        p = i;
        break;
    }
    for(int i = p; i <= n; i++) B[i-p+1] = A[i];
    for(int i = 1; i < p; i++) B[n-p+i+1] = A[i];
    B[n+1] = B[1];
    for(int i = 1; i <= n + 1; i++){
        l[i] = i;
        while(top and B[stk[top]]<=B[i]) l[i] = l[stk[top--]];
        stk[++top] = i;
    }
    top = 0;
    for(int i = n + 1; i >= 1; i--){
        r[i] = i; cnt[i] = 1;
        while(top and B[stk[top]]<=B[i]){
            if(B[stk[top]]==B[i]) cnt[i] += cnt[stk[top]];
            r[i] = r[stk[top--]];
        }
        stk[++top] = i;
    }
    int maxcnt = 0;
    for(int i = 1; i <= n; i++) if(B[i]==maxx) maxcnt++;
    LL ret = maxcnt * (maxcnt - 1ll) / 2;
    for(int i = 1; i <= n; i++) if(B[i]!=maxx){
        if(r[i] - l[i] + 2 == n) ret += 1;
        else ret += 2;
        ret += cnt[i] - 1;
    }
    cout << ret << endl;
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("Local.in","r",stdin);
    freopen("ans.out","w",stdout);
    #endif
    solve();
    return 0;
}


#include <iostream>
%:pragma GCC optimize(3)
%:pragma GCC optimize("Ofast")
%:pragma GCC optimize("inline")
%:pragma GCC optimize("-fgcse")
%:pragma GCC optimize("-fgcse-lm")
%:pragma GCC optimize("-fipa-sra")
%:pragma GCC optimize("-ftree-pre")
%:pragma GCC optimize("-ftree-vrp")
%:pragma GCC optimize("-fpeephole2")
%:pragma GCC optimize("-ffast-math")
%:pragma GCC optimize("-fsched-spec")
%:pragma GCC optimize("unroll-loops")
%:pragma GCC optimize("-falign-jumps")
%:pragma GCC optimize("-falign-loops")
%:pragma GCC optimize("-falign-labels")
%:pragma GCC optimize("-fdevirtualize")
%:pragma GCC optimize("-fcaller-saves")
%:pragma GCC optimize("-fcrossjumping")
%:pragma GCC optimize("-fthread-jumps")
%:pragma GCC optimize("-funroll-loops")
%:pragma GCC optimize("-fwhole-program")
%:pragma GCC optimize("-freorder-blocks")
%:pragma GCC optimize("-fschedule-insns")
%:pragma GCC optimize("inline-functions")
%:pragma GCC optimize("-ftree-tail-merge")
%:pragma GCC optimize("-fschedule-insns2")
%:pragma GCC optimize("-fstrict-aliasing")
%:pragma GCC optimize("-fstrict-overflow")
%:pragma GCC optimize("-falign-functions")
%:pragma GCC optimize("-fcse-skip-blocks")
%:pragma GCC optimize("-fcse-follow-jumps")
%:pragma GCC optimize("-fsched-interblock")
%:pragma GCC optimize("-fpartial-inlining")
%:pragma GCC optimize("no-stack-protector")
%:pragma GCC optimize("-freorder-functions")
%:pragma GCC optimize("-findirect-inlining")
%:pragma GCC optimize("-fhoist-adjacent-loads")
%:pragma GCC optimize("-frerun-cse-after-loop")
%:pragma GCC optimize("inline-small-functions")
%:pragma GCC optimize("-finline-small-functions")
%:pragma GCC optimize("-ftree-switch-conversion")
%:pragma GCC optimize("-foptimize-sibling-calls")
%:pragma GCC optimize("-fexpensive-optimizations")
%:pragma GCC optimize("-funsafe-loop-optimizations")
%:pragma GCC optimize("inline-functions-called-once")
%:pragma GCC optimize("-fdelete-null-pointer-checks")
using namespace std;
const int maxn=4000000;
int a[maxn],mx,p,h[maxn];
int main()
{
	int n;
	cin>>n;
	for (int i=0;i<n;i++) {
		cin>>a[i];
		if (a[i]>mx) {
			mx=a[i];
			p=i;
		}
	}
	int l[maxn],r[maxn],c[maxn];
	for (int i=0;i<=n;i++) h[i]=a[(p+i)%n];
	for (int i=1;i<=n;i++) {
		l[i]=i-1;
		while (h[i]>=h[l[i]] && l[i]) l[i]=l[l[i]];
	}
	for (int i=n-1;i>=0;i--){
		r[i]=i+1;
		while (h[i]>h[r[i]] && r[i]<n) r[i]=r[r[i]];
		if (r[i]<n && h[i]==h[r[i]]) {
			c[i]=c[r[i]]+1;
			r[i]=r[r[i]];
		}
	}
	long long ans=0;
	for (int i=0;i<n;i++){
		ans+=c[i];
		if (h[i]<h[0]) {
			ans+=2;
			if (l[i]==0 && r[i]==n) ans--;
		}
	}
	cout<<ans<<endl;
	return 0;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iomanip>
#include<algorithm>
#include<ctime>
#include<fstream>
#include<cstdlib>
#include<Windows.h>
#include<conio.h>
#define ll int
using namespace std;
ll read()
{
	char c=getchar();
	ll s=0,t=1;
	while(c<'0'||c>'9')
	{
		if(c=='-')t*=-1;
		c=getchar();
	}
	while(c>='0'&&c<='9')
	{
		s=s*10+c-'0';
		c=getchar();
	}
	return s*t;
}
ll n,h[3000001],l[3000001],r[3000001],k,fw,bj[3000001];
long long answer=0,cou=0;
ll findleft(ll x,ll high)
{
	if(n<1)return 0;
	if(h[x]>=high)return x;
	if(l[x])return findleft(l[x],high);
	else return findleft(x-1,high);
}
ll findright(ll x,ll high)
{
	if(x>n*3)return n*3+1;
	if(h[x]>=high)return x;
	if(r[x])return findright(r[x],high);
	else return findright(x+1,high);
}
void getleft(ll x,ll ini)
{
	if(x<=ini-n||x<=bj[ini])
	{
		return;
	}
	answer++;

	bj[x+n]=max(bj[x+n],ini);

/*	if(n<x)
	{
		cou++;
		cout<<"COUNT\n";
	}*/

//	cout<<ini<<' '<<x<<endl;

	if(h[x]>h[ini])
	{
		fw=x;
		return;
	}
	getleft(l[x],ini);
}
/*void getright(ll x,ll ini,ll lim)
{
	if(x>=ini+n||x>=lim)
	{
		return;
	}
	answer++;

	if(x<=n*2)
	{
		cou++;
		cout<<"COUNT\n";
	}

	cout<<ini<<' '<<x<<endl;

	if(h[x]>h[ini])
	{
		return;
	}
	getright(r[x],ini,lim);
}*/
int main()
{
	n=read();
	for(ll i=1;i<=n;i++)
	{
		k=read();
		h[i]=h[i+n]=h[i+2*n]=k;
	}
	for(ll i=n+1;i<=2*n;i++)
	{
		l[i]=findleft(i-1,h[i]);
		l[i-n]=l[i]-n;
		if(l[i-n]<0)l[i-n]=0;
		l[i+n]=l[i]+n;
	}
/*	for(ll i=2*n;i>=n+1;i--)
	{
		r[i]=findright(i+1,h[i]);
		r[i+n]=r[i]+n;
		if(r[i+n]>3*n)r[i+n]=3*n+1;
		r[i-n]=r[i]-n;
	}*/
	for(ll i=n+1;i<=n*2;i++)
	{
		getleft(i-1,i);
	}
	printf("%lld\n",answer);
}


#include <iostream>
using namespace std;
const int maxn=4000000;
int a[maxn],mx,p,h[maxn];
int main()
{
	int n;
	cin>>n;
	for (int i=0;i<n;i++) {
		cin>>a[i];
		if (a[i]>mx) {
			mx=a[i];
			p=i;
		}
	}
	int l[maxn],r[maxn],c[maxn];
	for (int i=0;i<=n;i++) h[i]=a[(p+i)%n];
	for (int i=1;i<=n;i++) {
		l[i]=i-1;
		while (h[i]>=h[l[i]] && l[i]) l[i]=l[l[i]];
	}
	for (int i=n-1;i>=0;i--){
		r[i]=i+1;
		while (h[i]>h[r[i]] && r[i]<n) r[i]=r[r[i]];
		if (r[i]<n && h[i]==h[r[i]]) {
			c[i]=c[r[i]]+1;
			r[i]=r[r[i]];
		}
	}
	int ans=0;
	for (int i=0;i<n;i++){
		ans+=c[i];
		if (h[i]<h[0]) {
			ans+=2;
			if (l[i]==0 && r[i]==n) ans--;
		}
	}
	cout<<ans<<endl;
	return 0;
}


#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
using namespace std;

class hill{
	public:
	hill* prev;
	hill* next;
	int height;
};
hill hills[100000];

int main(){
	int n;
	cin>>n;

	cin>>hills[1].height;
	hills[1].next=*(hills[2]);
	hills[1].prev=*(hills[n]);
	for(int i=2;i<=n-1;i++){
		cin>>hills[i].height;
		hills[i].next=*(hills[i+1]);
		hills[i].prev=*(hills[i-1]);
	}
	cin>>hills[n].height;
	hills[n].next=*(hills[1]);
	hills[n].prev=*(hills[n-1]);

}


#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5,inf=1e9+5;
int n,a[N],b[N],pos,ans;
int stk[N],r[N],cnt[N],nxt[N],top;
int rd()
{
	char ch='!'; int res=0;
	while(ch<'0' || ch>'9') ch=getchar();
	while(ch>='0' && ch<='9') res=res*10+ch-'0',ch=getchar();
	return res;
}
int main()
{
//	freopen("promise.in","r",stdin); freopen("promise.out","w",stdout);
	int c=0;
	n=rd(),pos=0,ans=0;
	for(int i=1;i<=n+1;++i) cnt[i]=0;
	for(int i=1;i<=n;++i) a[i]=rd();
	for(int i=1;i<=n;++i) if(a[pos]<a[i]) pos=i;
	for(int i=pos+1;i<=n;++i) b[++c]=a[i];
	for(int i=1;i<pos;++i) b[++c]=a[i];
	b[n]=a[pos],top=0,stk[0]=n+1,b[n+1]=inf;
	for(int i=n;i;--i)
	{
		while(top && b[stk[top]]<=b[i]) --top;
		r[i]=stk[top],stk[++top]=i;
	}
	top=0,stk[0]=n;
	for(int i=n-1;i;--i)
	{
		while(top && b[stk[top]]<b[i]) --top;
		cnt[i]=cnt[stk[top]]+1,nxt[i]=stk[top],stk[++top]=i;
		ans+=cnt[i+1]-cnt[r[i]]+1;
	}
	for(int i=1;i!=n;i=nxt[i]) if(r[i]<n) ++ans;
	printf("%d\n",ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
inline int read()
{
	int sign=1,sum=0;
	char c=getchar();
	while(!isdigit(c))
	{
		if (c=='-') sign=-1;
		c=getchar();
	}
	while(isdigit(c))
	{
		sum=(sum<<1)+(sum<<3)+c-'0';
		c=getchar();
	}
	return sign*sum;
}
#define read(x) x=read()
#define ll long long
const int N=1e6+50;
int n;
int a[N],h[N],l[N],r[N],cnt[N];
int main()
{
	read(n);
	for (int i=0;i<n;++i)
	  read(a[i]);
	int p=0;
	for (int i=1;i<n;++i)
	  if (a[i]>a[p])
	    p=i;
	for (int i=0;i<=n;++i)
	  h[i]=a[(i+p)%n];
	for (int i=1;i<=n;++i)
	  {
	  	l[i]=i-1;
	  	while(l[i]&&h[i]>=h[l[i]])
	  	  l[i]=l[l[i]];
	  }
	for (int i=n-1;i>=0;--i)
	{
		r[i]=i+1;
		while(r[i]<n&&h[i]>h[r[i]])
		  r[i]=r[r[i]];
		if (r[i]<n&&h[i]==h[r[i]])
		  cnt[i]=cnt[r[i]]+1,r[i]=r[r[i]];
	}
	ll ans=0;
	for (int i=0;i<n;++i)
	{
	  ans+=cnt[i];
	  if (h[i]<h[0])
	  {
	  	ans+=2;
	  	if (!l[i]&&r[i]==n)
	  	  --ans;
	  }
	}
	printf("%I64d\n",ans);
}


#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <map>
#include <queue>
#include <algorithm>
#define R register
#define ll long long
#define eps 1e-8
#define maxn 1000010
#define rep(i,s,n) for(R int i=s;i<=n;i++)
#define down(i,s,n) for(R int i=s;i>=n;i--)
using namespace std;
template <typename T>inline void in(R T&a)
{
	R char c=getchar();R T x=0,f=1;
	while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
	while(isdigit(c)){x=(x<<1)+(x<<3)+c-'0';c=getchar();}
	a=x*f;
}
template <typename T>inline int maxx(R T a,R T b){return a>b?a:b;}
template <typename T>inline int minn(R T a,R T b){return a<b?a:b;}
ll n,h[maxn],l[maxn],r[maxn],cnt[maxn],t[maxn];
int main()
{
	in(n);rep(i,0,n-1)in(t[i]);ll p=0;
	ll ans=0;rep(i,1,n-1)if(t[i]>t[p])p=i;rep(i,0,n)h[i]=t[(i+p)%n];
	rep(i,1,n){l[i]=i-1;while(l[i]&&h[i]>=h[l[i]])l[i]=l[l[i]];}
	down(i,n-1,0){r[i]=i+1;while(r[i]<n&&h[i]>h[r[i]])r[i]=r[r[i]];if(r[i]<n&&h[i]==h[r[i]])cnt[i]=cnt[r[i]]+1,r[i]=r[r[i]];}
	rep(i,0,n-1){ans+=cnt[i];if(h[i]<h[0]){ans+=2;if(!l[i]&&r[i]==n)ans--;}}
	cout<<ans<<endl;
	return 0;
}


#include<cstdio>
#include<cctype>
#include<queue>
#define pprint(x) ::print(x),putchar(' ')
#define fprint(x) ::print(x),putchar('\n')
using namespace std;
long long read()
{
	long long x = 0;int f = 1;
	char ch = getchar();
	for(;!isdigit(ch);ch = getchar())
		if(ch == '-')
			f = -1;
	for(;isdigit(ch);ch = getchar())
		x = x * 10 + (ch ^ 48);
	return x * f;
}
void print(long long x)
{
	if(x < 0)
		x = -x,putchar('-');
	if(x > 9)
		print(x / 10);
	putchar(x % 10 + '0');
}

const int N = 1000010;
int n,a[N],b[N];
int maxx,l[N],r[N],c[N];
long long ans;
int main()
{
	n = read();
	int st;
	for(int i = 0;i < n;i++)
	{
		b[i] = read();
		if(b[i] > maxx)
		{
			maxx = b[i];
			st = i;
		}
	}
	st--;
	for(int i = 1;i <= n;i++)
		a[i] = b[(i + st) % n];
	l[1] = 1;
	for(int i = 2;i <= n;i++)
	{
		l[i] = i - 1;
		while(l[i] > 1 && a[l[i]] <= a[i])
			l[i] = l[l[i]];
	}
	for(int i = n;i >= 1;i--)
	{
		r[i] = i + 1;
		while(r[i] <= n && a[r[i]] < a[i])
			r[i] = r[r[i]];
		if(r[i] <= n && a[r[i]] == a[i])
		{
			c[i] = c[r[i]] + 1;
			r[i] = r[r[i]];
		}
	}
	for(int i = 2;i <= n;i++)
	{
		ans += c[i] + 2;
		if(l[i] == 1 && r[i] == n + 1)
			ans--;
	}
	fprint(ans);
}


#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
const int MAXN=1e6+50;
typedef long long ll;
struct mt
{
    ll high,num;
    mt(){high=0;num=1;}
};
ll n,ans,a[MAXN],v[MAXN],imax,pos;
stack<mt> S;
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        imax=max(a[i],imax);
    }
    for(int i=1;i<=n;i++)
        if(a[i]==imax)
        {
            pos=i;
            break;
        }
    int pos2=pos,pos3=pos;
    for(int i=1;i<n;i++)
    {
        if(pos2==n) pos2=0;
        mt x;
        x.high=a[++pos2];
        if(S.empty())   S.push(x);
        else
        {
            if(x.high>=S.top().high)
            {
                if(x.high>=S.top().high)
                {
                while(!S.empty()&&x.high>S.top().high)  ans+=S.top().num,S.pop();
                if(!S.empty()&&x.high==S.top().high)    ans+=S.top().num,S.top().num+=x.num;
                else S.push(x);
                if(S.size()!=1) ans++;
                }
            }
            else S.push(x),ans++;
        }
    }
    int max=0;
    for(int i=1;i<n;i++)
    {
        if(pos3==n) pos3=0;
        int x=a[++pos3];
        if(x>=max)  v[pos3]=1,max=x;
    }
    max=0;
    for(int i=1;i<n;i++)
    {
        if(pos==1)  pos=n+1;
        int x=a[--pos];
        if(x>=max)  v[pos]=1,max=x;
    }
    for(int i=1;i<=n;i++)
        if(v[i])    ans++;
    cout<<ans<<endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=1000010;
int a[maxn],b[maxn],lef[maxn],rig[maxn],c[maxn],n,mid,ma=-1;
ll ans;
int main()
{
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
        if(a[i]>ma)
        {
            ma=a[i];
            mid=i;
        }
    }
    mid--;
    for(int j=1;j<=n;j++)
        b[j]=a[(mid+j)%n];
    lef[1]=1;
    for(int i=2;i<=n;i++)
    {
        lef[i]=i-1;
        while(lef[i]>1&&b[lef[i]]<=b[i])
            lef[i]=lef[lef[i]];
    }
    for(int i=n;i>=1;i--)
    {
        rig[i]=i+1;
        while(rig[i]<=n&&b[rig[i]]<b[i])
            rig[i]=rig[rig[i]];
        if(rig[i]<=n&&b[rig[i]]==b[i])
        {
            c[i]=c[rig[i]]+1;
            rig[i]=rig[rig[i]];
        }
    }
    for(int i=2;i<=n;i++)
    {
        ans+=c[i]+2;
        if(lef[i]==1&&rig[i]==n+1)
            ans--;
    }
    printf("%lld\n",ans);
  return 0;
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
#include<cctype>
using namespace std;
#define inf 0x3f3f3f3f
#define sint short int
#define reg register int
#define ll long long
#define ull unsigned long long
#define int128 __int128
inline int in(){
    reg ret=0,c=getchar(),b=1;
    while(!isdigit(c)){
        b=c=='-'?-1:1,c=getchar();
    }
    while(isdigit(c)){
        ret=ret*10+c-'0',c=getchar();
    }
    return ret*b;
}
#define in(x) x=in()
int a[1000005],b[1000005],l[1000005],r[1000005],cnt[1000005],n,mid,maxx=-1;
ll ans;
int main(){
    in(n);
    for(int i=0;i<n;i++){
        in(a[i]);
        if(a[i]>maxx){
            maxx=a[i];
            mid=i;
        }
    }
    mid--;
    for(int j=1;j<=n;j++){
        b[j]=a[(mid+j)%n];
    }
    l[1]=1;
    for(int i=2;i<=n;i++){
        l[i]=i-1;
        while(l[i]>1&&b[l[i]]<=b[i]){
            l[i]=l[l[i]];
        }
    }
    for(int i=n;i>=1;i--){
        r[i]=i+1;
        while(r[i]<=n&&b[r[i]]<b[i]){
            r[i]=r[r[i]];
        }
        if(r[i]<=n&&b[r[i]]==b[i]){
            cnt[i]=cnt[r[i]]+1;
            r[i]=r[r[i]];
        }
    }
    for(int i=2;i<=n;i++){
        ans+=cnt[i]+2;
        if(l[i]==1&&r[i]==n+1){
            ans--;
        }
    }
    printf("%lld\n",ans);
    return 0;
}


#include <cstdio>
#include <queue>
using namespace std;
int l[1000005], r[1000005], h[1000005], t[1000005], cnt[1000005];
priority_queue<int> Q;
int main()
{
    int n, p = 0;
    long long ans = 0;
    scanf("%d", &n);
    for(register int i = 0; i < n; i += 1)
    {
        scanf("%d", &t[i]);
        if(t[i] > t[p])
            p = i;
    }
    for(register int i = 0; i < n; i += 1)
        h[i] = t[(i+p)%n];
    for(register int i = 1; i < n; i += 1)
    {
        l[i] = i-1;
        while(l[i] && h[i] >= h[l[i]])
            l[i] = l[l[i]];
    }
    for(register int i = n-1; i >= 0; i -= 1)
    {
        r[i] = i+1;
        while(r[i] < n && h[i] > h[r[i]])
            r[i] = r[r[i]];
        if(r[i] < n && h[i] == h[r[i]])
        {
            cnt[i] = cnt[r[i]] + 1;
            r[i] = r[r[i]];
        }
    }
    for(register int i = 0; i < n; i += 1)
    {
        ans += cnt[i];
        if(h[i] < h[0])
        {
            ans += 2;
            if(!l[i] && r[i] == n)
                ans -= 1;
        }
    }
    printf("%lld", ans);
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int maxn=2000000+10;
int n,a[maxn],cnt[maxn];long long ans,now;

struct State
{
	int val,id;
}q[maxn];

int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	int fir=0,sec=0,cnt1=0,cnt2=0;
	for(int i=1;i<=n;i++)
	{
		if(fir<a[i]) fir=a[i],cnt1=0;
		if(fir==a[i]) cnt1++;
	}
	if(cnt1==n) return printf("%I64d\n",1ll*n*(n-1)/2),0;
	for(int i=1;i<=n;i++)
	{
		if(a[i]==fir) continue;
		if(sec<a[i]) sec=a[i],cnt2=0;
		if(sec==a[i]) cnt2++;
	}
	ans=2*(((cnt1==1)?1:2)*cnt2+2*(n-cnt1-cnt2));
	for(int i=1;i<=n;i++) a[i+n]=a[i];
	int l=1,r=0;
	for(int i=1;i<2*n;i++)
	{
		while(l<=r&&q[l].id<=i-n) cnt[q[l].val]--,l++;
		while(l<=r&&q[r].val<a[i]) cnt[q[r].val]--,r--;
		if(i>=n&&l<=r&&q[r].val==a[i]) ((a[i]==fir)?now:ans)+=cnt[a[i]];
		q[++r]=(State){a[i],i};cnt[a[i]]++;
	}
	for(int i=l;i<=r;i++) cnt[q[i].val]--;
	l=1,r=0;
	for(int i=2*n;i>1;i--)
	{
		while(l<=r&&q[l].id>=i+n) cnt[q[l].val]--,l++;
		while(l<=r&&q[r].val<a[i]) cnt[q[r].val]--,r--;
		if(i<=n+1&&l<=r&&q[r].val==a[i]) ((a[i]==fir)?now:ans)+=cnt[a[i]];
		q[++r]=(State){a[i],i};cnt[a[i]]++;
	}
	printf("%I64d\n",ans/2+now/4);
	return 0;
}


#include <iostream>
#include <cstdio>
using namespace std;
const int N = 1000000+50;
int n, ans, sta[N*2], a[N*2], tail, ban, de[N*2];
struct node
{
	int from, to, nex;
}edge[N*8];
int head[N], cnt;
void add(int x, int y)
{
	edge[++cnt].from = x;edge[cnt].to = y;edge[cnt].nex = head[x];head[x] = cnt;
}
int main()
{
	ios::sync_with_stdio(false);cin.tie(NULL);
	cin >> n;
	for(int i = 1; i <= n; ++i)
	{
		cin >> a[i];
		add(i, i);
		a[i+n] = a[i];
	}
	for(int i = 1; i <= n; ++i)
	{
		while(sta[tail] <= a[i] && tail)
		{
			ans++;
			add(de[tail], i);
			tail--;
		}
		if(tail) {ans++;add(de[tail], i);}
		sta[++tail] = a[i], de[tail] = i;
	}
	ban = tail;
	int x, y;
	for(int i = n+1; i <= n*2; ++i)
	{
		while(sta[tail] <= a[i] && tail)
		{
			if(tail <= ban && i != de[tail]+n){
				x = min(i-n, de[tail]);y = max(i-n, de[tail]);
				for(int k = head[x]; k; k = edge[k].nex)
					if(edge[i].to == y){ans--;break;}
				ans++;
			}
			tail--;
		}
		sta[++tail] = a[i];
		if(tail == ban+1 && i != de[ban]+n){
				x = min(i-n, de[ban]);y = max(i-n, de[ban]);
				for(int k = head[x]; k; k = edge[k].nex)
					if(edge[i].to == y){ans--;break;}

			ans++;
		}
	}
	if(ans == 4) cout<<3<<endl;
	else cout<<ans<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const LL mod = 1e9 + 7;
const int N = 2000005;

int a[N], b[N], l[N], r[N], e[N];
int main() {
    int n;
    scanf("%d", &n);
    int t = 0;
    for (int i = 0; i < n; i++) {
        scanf("%d", &b[i]);
        if (b[i] > b[t]) t = i;
    }
    for (int i = 1; i <= n; i++) {
        a[i] = b[(t + i - 1) % n];
    }
    a[0] = a[n + 1] = INF;
    for (int i = 1; i <= n; i++) {
        l[i] = i;
        while (a[i] >= a[l[i] - 1]) l[i] = l[l[i] - 1];
    }
    for (int i = n; i >= 1; i--) {
        r[i] = i;
        while (a[i] > a[r[i] + 1]) r[i] = r[r[i] + 1];
        if (a[i] == a[r[i] + 1]) {
            e[i] = e[r[i] + 1] + 1;
            r[i] = r[r[i] + 1];
        }
    }
    LL ans = 0;
    for (int i = 1; i <= n; i++) {
        if (l[i] != 1) ans++;
        if (r[i] != n) ans++;
        ans += e[i];
    }
    cout << ans << endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const double Pi = acos(-1);
namespace {
  template <typename T> inline void read(T &x) {
    x = 0; T f = 1;char s = getchar();
    for(; !isdigit(s); s = getchar()) if(s == '-') f = -1;
    for(;  isdigit(s); s = getchar()) x = (x << 3) + (x << 1) + (s ^ 48);
    x *= f;
  }
}
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define _for(n,m,i) for (register int i = (n); i <  (m); ++i)
#define _rep(n,m,i) for (register int i = (n); i <= (m); ++i)
#define _srep(n,m,i)for (register int i = (n); i >= (m); i--)
#define _sfor(n,m,i)for (register int i = (n); i >  (m); i--)
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define lowbit(x) x & (-x)
#define pii pair<int,int>
#define fi first
#define se second
const int N = 1e6+5;
int a[N], h[N], s[N], f[N];
int main() {
  int n, p = 1, top = 0; read(n);
  _for(0, n, i) read(a[i]), a[i] > a[p] && (p = i);
  _for(0, n, i) h[i] = a[(i+p)%n];
  LL ans = n-1;
  for(int i = 0; i < n; i++) {
    while(top && s[top] < h[i]) ans += f[top--];
    if(s[top] != h[i]) s[++top] = h[i], f[top] = 0;
    ans += f[top]++;
  }
  cout << ans << endl;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const double Pi = acos(-1);
namespace {
  template <typename T> inline void read(T &x) {
    x = 0; T f = 1;char s = getchar();
    for(; !isdigit(s); s = getchar()) if(s == '-') f = -1;
    for(;  isdigit(s); s = getchar()) x = (x << 3) + (x << 1) + (s ^ 48);
    x *= f;
  }
}
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define _for(n,m,i) for (register int i = (n); i <  (m); ++i)
#define _rep(n,m,i) for (register int i = (n); i <= (m); ++i)
#define _srep(n,m,i)for (register int i = (n); i >= (m); i--)
#define _sfor(n,m,i)for (register int i = (n); i >  (m); i--)
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define lowbit(x) x & (-x)
#define pii pair<int,int>
#define fi first
#define se second
const int N = 1e6+5;
int a[N], h[N], s[N], r[N], n, f[N];
void solve() {
  int top = 0;
  LL ans = 0;
  for(int i = 0; i < n; i++) {
    while(top && s[top] < h[i]) ans += f[top--] * 1ll * f[top];
    if(s[top] != h[i]) {
      s[++top] = h[i]; f[top] = 0;
    }
    ans += f[top]++;
  }
  while(top) ans += f[top--] * 1ll * f[top];
  for(int i = n-1; i >= 0; i--) {
    while(top && s[top] < h[i]) ans += f[top--] * 1ll * f[top];
    if(s[top] != h[i]) {
      s[++top] = h[i]; f[top] = 0;
    }
    f[top]++;
  }
  while(top) ans += f[top--] * 1ll * f[top];
  cout << ans << endl;
}
int main() {
  int p = 1, top = 0; read(n);
  _for(0, n, i) read(a[i]), a[i] > a[p] && (p = i);
  _for(0, n, i) h[i] = a[(i+p)%n];
  solve();
}


#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const double Pi = acos(-1);
namespace {
  template <typename T> inline void read(T &x) {
    x = 0; T f = 1;char s = getchar();
    for(; !isdigit(s); s = getchar()) if(s == '-') f = -1;
    for(;  isdigit(s); s = getchar()) x = (x << 3) + (x << 1) + (s ^ 48);
    x *= f;
  }
}
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define _for(n,m,i) for (register int i = (n); i <  (m); ++i)
#define _rep(n,m,i) for (register int i = (n); i <= (m); ++i)
#define _srep(n,m,i)for (register int i = (n); i >= (m); i--)
#define _sfor(n,m,i)for (register int i = (n); i >  (m); i--)
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define lowbit(x) x & (-x)
#define pii pair<int,int>
#define fi first
#define se second
const int N = 1e6+5;
int a[N], h[N], s[N], f[N];
int main() {
  int n, p = 1, top = 0; read(n);
  _for(0, n, i) read(a[i]), a[i] > a[p] && (p = i);
  _for(0, n, i) h[i] = a[(i+p)%n];
  LL ans = 0;
  s[top++] = h[0];
  for(int i = 1; i < n; i++) {
    while(top && s[top] < h[i]) ans += f[top--];
    if(s[top] != h[i]) s[++top] = h[i], f[top] = 0;
    ans += ++f[top];
  }
  cout << ans << endl;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const double Pi = acos(-1);
namespace {
  template <typename T> inline void read(T &x) {
    x = 0; T f = 1;char s = getchar();
    for(; !isdigit(s); s = getchar()) if(s == '-') f = -1;
    for(;  isdigit(s); s = getchar()) x = (x << 3) + (x << 1) + (s ^ 48);
    x *= f;
  }
}
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define _for(n,m,i) for (register int i = (n); i <  (m); ++i)
#define _rep(n,m,i) for (register int i = (n); i <= (m); ++i)
#define _srep(n,m,i)for (register int i = (n); i >= (m); i--)
#define _sfor(n,m,i)for (register int i = (n); i >  (m); i--)
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define lowbit(x) x & (-x)
#define pii pair<int,int>
#define fi first
#define se second
const int N = 1e6+5;
int a[N], h[N], s[N], r[N], n, f[N];
void solve() {
  int top = 0;
  LL ans = 0;
  for(int i = 0; i < n; i++) {
    while(top && s[top] < h[i]) ans += 2 * f[top--];
    if(s[top] != h[i]) s[++top] = h[i], f[top] = 0;
    ans += f[top]++;
  }
  if(f[1] == 1 && top > 1) ans -= f[2];
  while(top > 1) ans += 2 * f[top--];

  cout << ans << endl;
}
int main() {
  int p = 1, top = 0; read(n);
  _for(0, n, i) read(a[i]), a[i] > a[p] && (p = i);
  _for(0, n, i) h[i] = a[(i+p)%n];
  solve();
}


#include<bits/stdc++.h>

const int MAXN = 1e6+5;
int b[MAXN];
int fin[MAXN];
int ar[MAXN];
int f[MAXN];
using namespace std;
int main() {
// 	freopen("TASK.in","r",stdin);
// 	freopen("TASK.out","w",stdout);
	int n;
	cin>>n;
	int maxi=0;
	for(int i=1;i<=n;i++) scanf("%d",&ar[i]),maxi=max(maxi,ar[i]);
	for(int i=1;i<=n;i++) {
		if(ar[i]==maxi) {
			int counter=1;
			for(int j=i;j<=n;j++) fin[counter++]=ar[j];
			for(int j=1;j<i;j++) fin[counter++]=ar[j];
			break;
		}
	}
	for(int i=1;i<=n;i++) ar[i]=fin[i];
	ar[n+1]=maxi;
	stack<int> st;
	// for(int i=1;i<=n;i++) cout<<ar[i]<<" ";
	// cout<<endl;
	for(int i=1;i<=n;i++) {
		while(!st.empty() and ar[i]>=ar[st.top()]) st.pop();
		if(st.empty()) b[i]=0;
		else b[i]=st.top();
		st.push(i);
	}
	while(!st.empty()) st.pop();
	for(int i=n;i>=1;i--) {
		while(!st.empty() and ar[i]>=ar[st.top()]) st.pop();
		if(st.empty()) f[i]=n+1;
		else f[i]=st.top();
		st.push(i);
	}
	int counter=0;
	int freq=0;
	for(int i=1;i<=n;i++) {
		if(ar[i]==maxi) freq++;
		else if(b[i]==1 and f[i]==n+1) counter++;
		else counter+=2;
	}
	// for(int i=1;i<=n;i++) {
		// cout<<i<<" "<<b[i]<<" "<<f[i]<<endl;
	// }
	// cout<<freq<<" "<<counter<<endl;
	long long ans=freq;
	// cout<<ans<<endl;
	ans*=(ans-1LL);
	ans/=2LL;
	// cout<<ans<<endl;
	ans+=1LL*counter;
	cout<<ans<<endl;
	return 0;
}


#include<bits/stdc++.h>

const int MAXN = 1e6+5;
int b[MAXN];
int fin[MAXN];
int ar[MAXN];
int f[MAXN];
using namespace std;
int main() {
// 	freopen("TASK.in","r",stdin);
// 	freopen("TASK.out","w",stdout);
	int n;
	cin>>n;
	int maxi=0;
	for(int i=1;i<=n;i++) scanf("%d",&ar[i]),maxi=max(maxi,ar[i]);
	for(int i=1;i<=n;i++) {
		if(ar[i]==maxi) {
			int counter=1;
			for(int j=i;j<=n;j++) fin[counter++]=ar[j];
			for(int j=1;j<i;j++) fin[counter++]=ar[j];
			break;
		}
	}
	for(int i=1;i<=n;i++) ar[i]=fin[i];
	ar[n+1]=maxi;
	stack<int> st;
	for(int i=1;i<=n;i++) {
		while(!st.empty() and ar[i]>=ar[st.top()]) st.pop();
		if(st.empty()) b[i]=0;
		else b[i]=st.top();
		st.push(i);
	}
	while(!st.empty()) st.pop();
	for(int i=n;i>=1;i--) {
		while(!st.empty() and ar[i]>=ar[st.top()]) st.pop();
		if(st.empty()) f[i]=n+1;
		else f[i]=st.top();
		st.push(i);
	}
	int counter=0;
	int freq=0;
	for(int i=1;i<=n;i++) {
		if(ar[i]==maxi) freq++;
		else if(b[i]==1 and f[i]==n+1) counter++;
		else counter+=2;
	}
	long long ans=freq;
	ans*=(ans-1LL)/2LL;
	ans+=1LL*counter;
	cout<<ans<<endl;
	return 0;
}


#include<bits/stdc++.h>

const int MAXN = 1e6+5;
int b[MAXN];
int fin[MAXN];
int ar[MAXN];
int f[MAXN];
int bck[MAXN];
using namespace std;
int main() {
// 	freopen("TASK.in","r",stdin);
// 	freopen("TASK.out","w",stdout);
	int n;
	cin>>n;
	int maxi=0;
	for(int i=1;i<=n;i++) scanf("%d",&ar[i]),maxi=max(maxi,ar[i]);
	for(int i=1;i<=n;i++) {
		if(ar[i]==maxi) {
			int counter=1;
			for(int j=i;j<=n;j++) fin[counter++]=ar[j];
			for(int j=1;j<i;j++) fin[counter++]=ar[j];
			break;
		}
	}
	for(int i=1;i<=n;i++) ar[i]=fin[i];
	ar[n+1]=maxi;
	stack<int> st;
	// for(int i=1;i<=n;i++) cout<<ar[i]<<" ";
	// cout<<endl;
	for(int i=1;i<=n;i++) {
		while(!st.empty() and ar[i]>=ar[st.top()]) {
			if(ar[i]==ar[st.top()]) bck[i]=1+bck[st.top()];
			st.pop();
		}
		if(st.empty()) b[i]=0;
		else b[i]=st.top();
		st.push(i);
	}
	while(!st.empty()) st.pop();
	for(int i=n;i>=1;i--) {
		while(!st.empty() and ar[i]>=ar[st.top()]) st.pop();
		if(st.empty()) f[i]=n+1;
		else f[i]=st.top();
		st.push(i);
	}
	int counter=0;
	int freq=0;
	for(int i=1;i<=n;i++) {
		if(ar[i]==maxi) freq++;
		else if(b[i]==1 and f[i]==n+1) counter++,counter+=bck[i];
		else counter+=2,counter+=bck[i];
	}
	// for(int i=1;i<=n;i++) {
		// cout<<i<<" "<<b[i]<<" "<<f[i]<<endl;
	// }
	// cout<<freq<<" "<<counter<<endl;
	long long ans=freq;
	// cout<<ans<<endl;
	ans*=(ans-1LL);
	ans/=2LL;
	// cout<<ans<<endl;
	ans+=1LL*counter;
	cout<<ans<<endl;
	return 0;
}


#include<bits/stdc++.h>

const int MAXN = 1e6+5;
int b[MAXN];
int fin[MAXN];
int ar[MAXN];
int f[MAXN];
long long bck[MAXN];
using namespace std;
int main() {
// 	freopen("TASK.in","r",stdin);
// 	freopen("TASK.out","w",stdout);
	int n;
	cin>>n;
	int maxi=0;
	for(int i=1;i<=n;i++) scanf("%d",&ar[i]),maxi=max(maxi,ar[i]);
	for(int i=1;i<=n;i++) {
		if(ar[i]==maxi) {
			int counter=1;
			for(int j=i;j<=n;j++) fin[counter++]=ar[j];
			for(int j=1;j<i;j++) fin[counter++]=ar[j];
			break;
		}
	}
	for(int i=1;i<=n;i++) ar[i]=fin[i];
	ar[n+1]=maxi;
	stack<int> st;
	// for(int i=1;i<=n;i++) cout<<ar[i]<<" ";
	// cout<<endl;
	for(int i=1;i<=n;i++) {
		while(!st.empty() and ar[i]>=ar[st.top()]) {
			if(ar[i]==ar[st.top()]) bck[i]=1+bck[st.top()];
			st.pop();
		}
		if(st.empty()) b[i]=0;
		else b[i]=st.top();
		st.push(i);
	}
	while(!st.empty()) st.pop();
	for(int i=n;i>=1;i--) {
		while(!st.empty() and ar[i]>=ar[st.top()]) st.pop();
		if(st.empty()) f[i]=n+1;
		else f[i]=st.top();
		st.push(i);
	}
	long long counter=0;
	long long freq=0;
	for(int i=1;i<=n;i++) {
		if(ar[i]==maxi) freq++;
		else if(b[i]==1 and f[i]==n+1) counter++,counter+=bck[i];
		else counter+=2,counter+=bck[i];
	}
	// for(int i=1;i<=n;i++) {
		// cout<<i<<" "<<b[i]<<" "<<f[i]<<endl;
	// }
	// cout<<freq<<" "<<counter<<endl;
	long long ans=freq;
	// cout<<ans<<endl;
	ans*=(ans-1LL);
	ans/=2LL;
	// cout<<ans<<endl;
	ans+=1LL*counter;
	cout<<ans<<endl;
	return 0;
}


//~In The Name Of Allah~//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <sstream>
#include <cstring>
#include <fstream>
#include <functional>
#include <cstdio>
#include <stack>
#include <utility>
#include <set>
#include <list>
#include <queue>
#include <bitset>
#include <time.h>
using namespace std;

#define all(S) S.begin(), S.end()
#define rall(S) S.rbegin(), S.rend()
#define sp(N) setprecision(N)<<fixed
#define siz(S) (int)S.size()
#define rep(i, j) for (int i = 0; i < int(j); i++)
#define Rep(i, j, k) for (int i = (int)j; i < (int)k; i++)
#define srep(S) for (auto it:S)
#define mem(U, V) memset(U, V, sizeof U)
#define getdis(xa, ya, xb, yb) hypot(xa-xb, ya-yb)
#define slope(xa, ya, xb, yb) (double)(((double)yb-(double)ya)/((double)xb-(double)xa))

#define Read() freopen("in.txt", "r", stdin)
#define Write() freopen("out.txt", "w", stdout)

typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<ll> vll;
typedef vector<string> vs;

const double PI = 2.0 * acos(0.0);
const double EX = 2.7182818284;
const int MOD = 1e9 + 7;
const int oo = 2e9 + 1e8;

int di[] = { 0, 1, 0, -1, 1, 1, -1, -1 };
int dj[] = { 1, 0, -1, 0, 1, -1, -1, 1 };
int dik[] = { -1, -1, 1, 1, -2, -2, 2, 2 };
int djk[] = { 2, -2, 2, -2, 1, -1, 1, -1 };

ll gcd(ll x, ll y){ return !y ? x : gcd(y, x%y); }

ll getInt(){
    ll ret;
    char tmpc;
    bool sign = 0;
    while (tmpc = getchar()){
        if (tmpc<'0' || tmpc>'9') sign = (tmpc == '-');
        else break;
    }
    ret = tmpc - '0';
    while (tmpc = getchar(), tmpc >= '0' && tmpc <= '9')
        ret = ret * 10 + tmpc - '0';
    if (sign) ret *= -1;
    return ret;
}

ll ans;
int n, idx, l[(int)1e6 + 10], r[(int)1e6 + 10];

int main(){
    n = getInt();
    vi tmp(n), in(n + 1), have(n);
    rep(i, n) tmp[i] = getInt();
    rep(i, n) if (tmp[i] > tmp[idx])
        idx = i;
    Rep(i, idx, n + idx)
        in[i - idx] = tmp[i%n];
    in[n] = in[0];
    for (int i = n - 1; i > -1; i--){
        r[i] = i + 1;
        while (r[i] < n && in[i] > in[r[i]])
            r[i] = r[r[i]];
        // 2 2 2 - 2
        // 0 1 0
        // 0
        if (r[i] < n && in[i] == in[r[i]])
            have[i] = have[r[i]] + 1;
    }
    Rep(i, 1, n){
        l[i] = i - 1;
        while (l[i] > 0 && in[i] >= in[l[i]])
            l[i] = l[l[i]];
    }
    rep(i, n){
        ans += have[i];
        if (in[i] != in[0]){
            ans += 2;
            if (!l[i] && r[i] == n)
                ans--;
        }
    }
    printf("%I64d\n", ans);
    return 0;
}


//~In The Name Of Allah~//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <sstream>
#include <cstring>
#include <fstream>
#include <functional>
#include <cstdio>
#include <stack>
#include <utility>
#include <set>
#include <list>
#include <queue>
#include <bitset>
#include <time.h>
using namespace std;

#define all(S) S.begin(), S.end()
#define rall(S) S.rbegin(), S.rend()
#define sp(N) setprecision(N)<<fixed
#define siz(S) (int)S.size()
#define rep(i, j) for (int i = 0; i < int(j); i++)
#define Rep(i, j, k) for (int i = (int)j; i < (int)k; i++)
#define srep(S) for (auto it:S)
#define mem(U, V) memset(U, V, sizeof U)
#define getdis(xa, ya, xb, yb) hypot(xa-xb, ya-yb)
#define slope(xa, ya, xb, yb) (double)(((double)yb-(double)ya)/((double)xb-(double)xa))

#define Read() freopen("in.txt", "r", stdin)
#define Write() freopen("out.txt", "w", stdout)

typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<ll> vll;
typedef vector<string> vs;

const double PI = 2.0 * acos(0.0);
const double EX = 2.7182818284;
const int MOD = 1e9 + 7;
const int oo = 2e9 + 1e8;

int di[] = { 0, 1, 0, -1, 1, 1, -1, -1 };
int dj[] = { 1, 0, -1, 0, 1, -1, -1, 1 };
int dik[] = { -1, -1, 1, 1, -2, -2, 2, 2 };
int djk[] = { 2, -2, 2, -2, 1, -1, 1, -1 };

ll gcd(ll x, ll y){ return !y ? x : gcd(y, x%y); }

ll getInt(){
    ll ret;
    char tmpc;
    bool sign = 0;
    while (tmpc = getchar()){
        if (tmpc<'0' || tmpc>'9') sign = (tmpc == '-');
        else break;
    }
    ret = tmpc - '0';
    while (tmpc = getchar(), tmpc >= '0' && tmpc <= '9')
        ret = ret * 10 + tmpc - '0';
    if (sign) ret *= -1;
    return ret;
}

ll ans;
int n, idx, l[(int)1e6 + 10], r[(int)1e6 + 10];

int main(){
    n = getInt();
    vi tmp(n), in(n + 1), have(n);
    rep(i, n) tmp[i] = getInt();
    rep(i, n) if (tmp[i] > tmp[idx])
        idx = i;
    Rep(i, idx, n + idx)
        in[i - idx] = tmp[i%n];
    in[n] = in[0];
    for (int i = n - 1; i > -1; i--){
        r[i] = i + 1;
        while (r[i] < n && in[i] > in[r[i]])
            r[i] = r[r[i]];
        if (r[i] < n && in[i] == in[r[i]]){
            have[i] = have[r[i]] + 1;
            ans += have[i];
            r[i] = r[r[i]];
        }
    }
    Rep(i, 1, n){
        l[i] = i - 1;
        while (l[i] > 0 && in[i] >= in[l[i]])
            l[i] = l[l[i]];
    }
    Rep(i, 1, n) if (in[i] != in[0]){
        ans += 2;
        if (!l[i] && r[i] == n)
            ans--;
    }
    printf("%I64d\n", ans);
    return 0;
}


//~In The Name Of Allah~//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <sstream>
#include <cstring>
#include <fstream>
#include <functional>
#include <cstdio>
#include <stack>
#include <utility>
#include <set>
#include <list>
#include <queue>
#include <bitset>
#include <time.h>
using namespace std;

#define all(S) S.begin(), S.end()
#define rall(S) S.rbegin(), S.rend()
#define sp(N) setprecision(N)<<fixed
#define siz(S) (int)S.size()
#define rep(i, j) for (int i = 0; i < int(j); i++)
#define Rep(i, j, k) for (int i = (int)j; i < (int)k; i++)
#define srep(S) for (auto it:S)
#define mem(U, V) memset(U, V, sizeof U)
#define getdis(xa, ya, xb, yb) hypot(xa-xb, ya-yb)
#define slope(xa, ya, xb, yb) (double)(((double)yb-(double)ya)/((double)xb-(double)xa))

#define Read() freopen("in.txt", "r", stdin)
#define Write() freopen("out.txt", "w", stdout)

typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<ll> vll;
typedef vector<string> vs;

const double PI = 2.0 * acos(0.0);
const double EX = 2.7182818284;
const int MOD = 1e9 + 7;
const int oo = 2e9 + 1e8;

int di[] = { 0, 1, 0, -1, 1, 1, -1, -1 };
int dj[] = { 1, 0, -1, 0, 1, -1, -1, 1 };
int dik[] = { -1, -1, 1, 1, -2, -2, 2, 2 };
int djk[] = { 2, -2, 2, -2, 1, -1, 1, -1 };

ll gcd(ll x, ll y){ return !y ? x : gcd(y, x%y); }

ll getInt(){
    ll ret;
    char tmpc;
    bool sign = 0;
    while (tmpc = getchar()){
        if (tmpc<'0' || tmpc>'9') sign = (tmpc == '-');
        else break;
    }
    ret = tmpc - '0';
    while (tmpc = getchar(), tmpc >= '0' && tmpc <= '9')
        ret = ret * 10 + tmpc - '0';
    if (sign) ret *= -1;
    return ret;
}

int n, idx, ans, l[(int)1e6 + 10], r[(int)1e6 + 10];

int main(){
    n = getInt();
    vi tmp(n), in(n + 1), have(n);
    rep(i, n) tmp[i] = getInt();
    rep(i, n) if (tmp[i] > tmp[idx])
        idx = i;
    Rep(i, idx, n + idx)
        in[i - idx] = tmp[i%n];
    in[n] = in[0];
    for (int i = n - 1; i > -1; i--){
        r[i] = i + 1;
        while (r[i] < n && in[i] > in[r[i]])
            r[i] = r[r[i]];
        // 2 2 2 - 2
        // 0 1 0
        // 0
        if (r[i] < n && in[i] == in[r[i]])
            have[i] = have[r[i]] + 1;
    }
    Rep(i, 1, n){
        l[i] = i - 1;
        while (l[i] > 0 && in[i] >= in[l[i]])
            l[i] = l[l[i]];
    }
    rep(i, n){
        ans += have[i];
        if (in[i] != in[0]){
            ans += 2;
            if (!l[i] && r[i] == n)
                ans--;
        }
    }
    printf("%d\n", ans);
    return 0;
}


//~In The Name Of Allah~//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <sstream>
#include <cstring>
#include <fstream>
#include <functional>
#include <cstdio>
#include <stack>
#include <utility>
#include <set>
#include <list>
#include <queue>
#include <bitset>
#include <time.h>
using namespace std;

#define all(S) S.begin(), S.end()
#define rall(S) S.rbegin(), S.rend()
#define sp(N) setprecision(N)<<fixed
#define siz(S) (int)S.size()
#define rep(i, j) for (int i = 0; i < int(j); i++)
#define Rep(i, j, k) for (int i = (int)j; i < (int)k; i++)
#define srep(S) for (auto it:S)
#define mem(U, V) memset(U, V, sizeof U)
#define getdis(xa, ya, xb, yb) hypot(xa-xb, ya-yb)
#define slope(xa, ya, xb, yb) (double)(((double)yb-(double)ya)/((double)xb-(double)xa))

#define Read() freopen("in.txt", "r", stdin)
#define Write() freopen("out.txt", "w", stdout)

typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<ll> vll;
typedef vector<string> vs;

const double PI = 2.0 * acos(0.0);
const double EX = 2.7182818284;
const int MOD = 1e9 + 7;
const int oo = 2e9 + 1e8;

int di[] = { 0, 1, 0, -1, 1, 1, -1, -1 };
int dj[] = { 1, 0, -1, 0, 1, -1, -1, 1 };
int dik[] = { -1, -1, 1, 1, -2, -2, 2, 2 };
int djk[] = { 2, -2, 2, -2, 1, -1, 1, -1 };

ll gcd(ll x, ll y){ return !y ? x : gcd(y, x%y); }

ll getInt(){
    ll ret;
    char tmpc;
    bool sign = 0;
    while (tmpc = getchar()){
        if (tmpc<'0' || tmpc>'9') sign = (tmpc == '-');
        else break;
    }
    ret = tmpc - '0';
    while (tmpc = getchar(), tmpc >= '0' && tmpc <= '9')
        ret = ret * 10 + tmpc - '0';
    if (sign) ret *= -1;
    return ret;
}

int n, idx, ans, l[(int)1e6 + 10], r[(int)1e6 + 10];

int main(){
    n = getInt();
    vi tmp(n), in(n + 1);
    rep(i, n) tmp[i] = getInt();
    rep(i, n) if (tmp[i] > tmp[idx])
        idx = i;
    Rep(i, idx, n + idx)
        in[i - idx] = tmp[i%n];
    in[n] = in[0];
    for (int i = n - 1; i > -1; i--){
        r[i] = i + 1;
        while (r[i] < n && in[i]>in[r[i]])
            r[i] = r[r[i]];
    }
    Rep(i, 1, n){
        l[i] = i - 1;
        while (l[i] > 0 && in[i] > in[l[i]])
            l[i] = l[l[i]];
    }
    rep(i, n) if (in[i] != in[0]){
        ans += 2;
        if (!l[i] && r[i] == n)
            ans--;
    }
    printf("%d\n", ans);
    return 0;
}


//~In The Name Of Allah~//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <sstream>
#include <cstring>
#include <fstream>
#include <functional>
#include <cstdio>
#include <stack>
#include <utility>
#include <set>
#include <list>
#include <queue>
#include <bitset>
#include <time.h>
using namespace std;

#define all(S) S.begin(), S.end()
#define rall(S) S.rbegin(), S.rend()
#define sp(N) setprecision(N)<<fixed
#define siz(S) (int)S.size()
#define rep(i, j) for (int i = 0; i < int(j); i++)
#define Rep(i, j, k) for (int i = (int)j; i < (int)k; i++)
#define srep(S) for (auto it:S)
#define mem(U, V) memset(U, V, sizeof U)
#define getdis(xa, ya, xb, yb) hypot(xa-xb, ya-yb)
#define slope(xa, ya, xb, yb) (double)(((double)yb-(double)ya)/((double)xb-(double)xa))

#define Read() freopen("in.txt", "r", stdin)
#define Write() freopen("out.txt", "w", stdout)

typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<ll> vll;
typedef vector<string> vs;

const double PI = 2.0 * acos(0.0);
const double EX = 2.7182818284;
const int MOD = 1e9 + 7;
const int oo = 2e9 + 1e8;

int di[] = { 0, 1, 0, -1, 1, 1, -1, -1 };
int dj[] = { 1, 0, -1, 0, 1, -1, -1, 1 };
int dik[] = { -1, -1, 1, 1, -2, -2, 2, 2 };
int djk[] = { 2, -2, 2, -2, 1, -1, 1, -1 };

ll gcd(ll x, ll y){ return !y ? x : gcd(y, x%y); }

ll getInt(){
    ll ret;
    char tmpc;
    bool sign = 0;
    while (tmpc = getchar()){
        if (tmpc<'0' || tmpc>'9') sign = (tmpc == '-');
        else break;
    }
    ret = tmpc - '0';
    while (tmpc = getchar(), tmpc >= '0' && tmpc <= '9')
        ret = ret * 10 + tmpc - '0';
    if (sign) ret *= -1;
    return ret;
}

ll ans;
int n, idx, l[(int)1e6 + 10], r[(int)1e6 + 10];

int main(){
    n = getInt();
    vi tmp(n), in(n + 1), have(n);
    rep(i, n) tmp[i] = getInt();
    rep(i, n) if (tmp[i] > tmp[idx])
        idx = i;
    Rep(i, idx, n + idx)
        in[i - idx] = tmp[i%n];
    in[n] = in[0];
    for (int i = n - 1; i > -1; i--){
        r[i] = i + 1;
        while (r[i] < n && in[i] > in[r[i]])
            r[i] = r[r[i]];
        if (r[i] < n && in[i] == in[r[i]]){
            have[i] = have[r[i]] + 1;
            ans += have[i];
            r[i] = r[r[i]];
        }
    }
    Rep(i, 1, n){
        l[i] = i - 1;
        while (l[i] > 0 && in[i] >= in[l[i]])
            l[i] = l[l[i]];
    }
    rep(i, n) if (in[i] != in[0]){
        ans += 2;
        if (!l[i] && r[i] == n)
            ans--;
    }
    printf("%I64d\n", ans);
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int LEN = 200005;
char STR[LEN],*ST = STR,*ED = STR;
inline char gc(){
	if(ST == ED){
		ED = (ST = STR) + fread(STR,1,LEN,stdin);
		if(ST == ED) return EOF;
	}
	return *ST++;
}
#define gc getchar
inline int read(){
	int x = 0,f = 1;char ch = gc();
	while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = gc();}
	while(ch >= '0' && ch <= '9'){x = x*10+ch-'0';ch = gc();}
	return x*f;
}

const int N = 1000005;
int a[N],top;
int d[N],n;
int num[N];
int Mx,cnt;
long long ans;

int main(){
	n = read();
	for(int i = 1;i <= n;++i){
		a[i] = read();
		if(Mx <= a[i]){
			Mx = a[i];
			cnt = i;
		}
	}
	for(int i = cnt;i <= n;++i)
		d[i-cnt+1] = a[i];
	for(int i = 1;i < cnt;++i)
		d[n-cnt+1+i] = a[i];
	top = 0;
	for(int i = 1;i <= n;++i){
		while(top > 0 && a[top] < d[i]){
			ans += num[top];
			--top;
		}
		if(top > 0 && a[top] == d[i]){
			ans += num[top];
			num[top]++;
			if(top > 1) ++ans;
		}
		else{
			if(top > 0) ++ans;
			a[++top] = d[i];
			num[top] = 1;
		}
	}
	printf("%lld\n", ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int LEN = 200005;
char STR[LEN],*ST = STR,*ED = STR;
inline char gc(){
	if(ST == ED){
		ED = (ST = STR) + fread(STR,1,LEN,stdin);
		if(ST == ED) return EOF;
	}
	return *ST++;
}
#define gc getchar
inline int read(){
	int x = 0,f = 1;char ch = gc();
	while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = gc();}
	while(ch >= '0' && ch <= '9'){x = x*10+ch-'0';ch = gc();}
	return x*f;
}

const int N = 1000005;
int a[N],top;
int d[N],n;
int num[N];
int Mx,cnt;
long long ans;

int main(){
	n = read();
	for(int i = 1;i <= n;++i){
		a[i] = read();
		if(Mx < a[i]){
			Mx = a[i];
			cnt = i;
		}
	}
	for(int i = cnt;i <= n;++i)
		d[i-cnt+1] = a[i];
	for(int i = 1;i < cnt;++i)
		d[n-cnt+1+i] = a[i];
	top = 0;
	for(int i = 1;i <= n;++i){
		while(top > 0 && a[top] < d[i]){
			ans += num[top];
			--top;
		}
		if(top > 0 && a[top] == d[i]){
			ans += num[top];
			num[top]++;
		}
		else{
			if(top > 0) ++ans;
			a[++top] = d[i];
			num[top] = 1;
		}
	}
	printf("%lld\n", ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int LEN = 200005;
char STR[LEN],*ST = STR,*ED = STR;
inline char gc(){
	if(ST == ED){
		ED = (ST = STR) + fread(STR,1,LEN,stdin);
		if(ST == ED) return EOF;
	}
	return *ST++;
}
inline int read(){
	int x = 0,f = 1;char ch = gc();
	while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = gc();}
	while(ch >= '0' && ch <= '9'){x = x*10+ch-'0';ch = gc();}
	return x*f;
}

const int N = 1000005;
int a[N],top;
int d[N],n;
int Mx,cnt;
long long ans;

int main(){
	n = read();
	for(int i = 1;i <= n;++i){
		a[i] = read();
		if(Mx < a[i]){
			Mx = a[i];
			cnt = i;
		}
	}
	for(int i = cnt;i <= n;++i)
		d[i-cnt+1] = a[i];
	for(int i = 1;i < cnt;++i)
		d[n-cnt+1+i] = a[i];
	top = 0;
	for(int i = 1;i <= n;++i){
		while(top > 0 && a[top] < d[i]){
			--top;
			++ans;
		}
		if(top > 0) ++ans;
		a[++top] = d[i];
	}
	printf("%lld\n", ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int LEN = 200005;
char STR[LEN],*ST = STR,*ED = STR;
inline char gc(){
	if(ST == ED){
		ED = (ST = STR) + fread(STR,1,LEN,stdin);
		if(ST == ED) return EOF;
	}
	return *ST++;
}
#define gc getchar
inline int read(){
	int x = 0,f = 1;char ch = gc();
	while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = gc();}
	while(ch >= '0' && ch <= '9'){x = x*10+ch-'0';ch = gc();}
	return x*f;
}

const int N = 1000005;
int a[N],top;
int d[N],n;
int num[N];
int Mx,cnt;
long long ans;

int main(){
	n = read();
	for(int i = 1;i <= n;++i){
		a[i] = read();
		if(Mx < a[i]){
			Mx = a[i];
			cnt = i;
		}
	}
	for(int i = cnt;i <= n;++i)
		d[i-cnt] = a[i];
	for(int i = 1;i <= cnt;++i)
		d[n-cnt+i] = a[i];
	top = 1; a[top] = d[0]; num[top] = 1;
	for(int i = 1;i <= n;++i){
		while(top > 0 && a[top] < d[i]){
			ans += num[top];
			--top;
		}
		if(top > 0 && a[top] == d[i]){
			ans += num[top];
			num[top]++;
			if(top > 1) ++ans;
		}
		else{
			if(top > 0) ++ans;
			a[++top] = d[i];
			num[top] = 1;
		}
	}
	if(num[1] == 2) ans -= num[2];
	ans -= num[1]-1;
	printf("%lld\n", ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int LEN = 200005;
char STR[LEN],*ST = STR,*ED = STR;
inline char gc(){
	if(ST == ED){
		ED = (ST = STR) + fread(STR,1,LEN,stdin);
		if(ST == ED) return EOF;
	}
	return *ST++;
}
#define gc getchar
inline int read(){
	int x = 0,f = 1;char ch = gc();
	while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = gc();}
	while(ch >= '0' && ch <= '9'){x = x*10+ch-'0';ch = gc();}
	return x*f;
}

const int N = 1000005;
int a[N],top;
int d[N],n;
int Mx,cnt;
long long ans;

int main(){
	n = read();
	for(int i = 1;i <= n;++i){
		a[i] = read();
		if(Mx < a[i]){
			Mx = a[i];
			cnt = i;
		}
	}
	for(int i = cnt;i <= n;++i)
		d[i-cnt+1] = a[i];
	for(int i = 1;i < cnt;++i)
		d[n-cnt+1+i] = a[i];
	top = 0;
	for(int i = 1;i <= n;++i){
		while(top > 0 && a[top] < d[i]){
			--top;
			++ans;
		}
		while(top > 1 && a[top-1] == a[top] && a[top] == d[i]){
			--top;
			++ans;
		}
		if(top > 0) ++ans;
		a[++top] = d[i];
	}
	printf("%lld\n", ans);
	return 0;
}


#include<bits/stdc++.h> ////
using namespace std;
const int LEN = 200005;
char STR[LEN],*ST = STR,*ED = STR;
inline char gc(){
	if(ST == ED){
		ED = (ST = STR) + fread(STR,1,LEN,stdin);
		if(ST == ED) return EOF;
	}
	return *ST++;
}
#define gc getchar
inline int read(){
	int x = 0,f = 1;char ch = gc();
	while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = gc();}
	while(ch >= '0' && ch <= '9'){x = x*10+ch-'0';ch = gc();}
	return x*f;
}

const int N = 1000005;
int a[N],top;
int d[N],n;
int num[N];
int Mx,cnt;
long long ans;

int main(){
	n = read();
	for(int i = 1;i <= n;++i){
		a[i] = read();
		if(Mx < a[i]){
			Mx = a[i];
			cnt = i;
		}
	}
	for(int i = cnt;i <= n;++i)
		d[i-cnt] = a[i];
	for(int i = 1;i <= cnt;++i)
		d[n-cnt+i] = a[i];
	top = 1; a[top] = d[0]; num[top] = 1;
	for(int i = 1;i <= n;++i){
		while(top > 0 && a[top] < d[i]){
			ans += num[top];
			--top;
		}
		if(top > 0 && a[top] == d[i]){
			ans += num[top];
			num[top]++;
			if(top > 1) ++ans;
		}
		else{
			if(top > 0) ++ans;
			a[++top] = d[i];
			num[top] = 1;
		}
	}
	if(num[1] == 2) ans -= num[2];
	ans -= num[1]-1;
	printf("%lld\n", ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define For(i,j,k) for(int i=(int)(j);i<=(int)(k);i++)
#define Rep(i,j,k) for(int i=(int)(j);i>=(int)(k);i--)
inline ll read(){
    ll x=0;char ch=getchar();bool f=0;
    for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=1;
    for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';
    return f?-x:x;
}
void write(ll x){
    if(x<0) putchar('-'),x=-x;
    if(x>=10) write(x/10);putchar(x%10+'0');
}
void writeln(ll x){write(x);puts("");}
void writep(ll x){write(x);putchar(' ');}

int const N=1e6+3;
int n,top,ans,a[N],b[N],st[N],l[N],r[N],f[N];

signed main(){
	n=read();
	int k=0;
	for (int i=1;i<=n;i++){
		b[i]=read();
		if (b[i]>=b[k]) k=i;
	}
	for (int i=1;i<=n;i++) a[i]=b[(k+i-2)%n+1];
	for (int i=1;i<=n;i++) l[i]=1,r[i]=n+1;
	for (int i=1;i<=n;i++){
		while (top&&a[st[top]]<=a[i]) top--;
		if (top) l[i]=st[top];
		st[++top]=i;
	}
	top=0;
	for (int i=n;i;i--){
		while (top&&a[st[top]]<a[i]) top--;
		if (top) r[i]=st[top];
		st[++top]=i;
		if (r[i]<=n&&a[r[i]]==a[i]){
			f[i]=f[r[i]]+1;
			r[i]=r[r[i]];
		}
	}
	for (int i=2;i<=n;i++){
		ans+=f[i]+2;
		if (l[i]==1&&r[i]==n+1) ans--;
	}
	writeln(ans);
	return 0;
}

/*
5
5 3 1 2 4

4
2 2 2 2

3
2 2 2

4
2 2 3 3
*/


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define For(i,j,k) for(int i=(int)(j);i<=(int)(k);i++)
#define Rep(i,j,k) for(int i=(int)(j);i>=(int)(k);i--)
inline ll read(){
    ll x=0;char ch=getchar();bool f=0;
    for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=1;
    for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';
    return f?-x:x;
}
void write(ll x){
    if(x<0) putchar('-'),x=-x;
    if(x>=10) write(x/10);putchar(x%10+'0');
}
void writeln(ll x){write(x);puts("");}
void writep(ll x){write(x);putchar(' ');}

int const N=1e6+3;
int n,top,ans,a[N],b[N],st[N];

signed main(){
	n=read();
	int k=0;
	for (int i=1;i<=n;i++){
		b[i]=read();
		if (b[i]>=b[k]) k=i;
	}
	for (int i=1;i<=n;i++) a[i]=b[(k+i-2)%n+1];
	// for (int i=1;i<=n;i++) cout<<a[i]<<' ';
	// cout<<endl;
	for (int i=1;i<=n;i++){
		while (top&&a[st[top]]<a[i]) top--,ans++;
		int p=top;
		while (p>0&&a[st[p]]>=a[i]){
			ans++;
			if (a[st[p]]>a[i]) break;
			p--;
		}
		st[++top]=i;
	}
	writeln(ans);
	return 0;
}

/*
5
5 3 1 2 4

4
2 2 2 2

3
2 2 2

4
2 2 3 3
*/


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define For(i,j,k) for(int i=(int)(j);i<=(int)(k);i++)
#define Rep(i,j,k) for(int i=(int)(j);i>=(int)(k);i--)
inline ll read(){
    ll x=0;char ch=getchar();bool f=0;
    for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=1;
    for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';
    return f?-x:x;
}
void write(ll x){
    if(x<0) putchar('-'),x=-x;
    if(x>=10) write(x/10);putchar(x%10+'0');
}
void writeln(ll x){write(x);puts("");}
void writep(ll x){write(x);putchar(' ');}

int const N=1e6+3;
int n,top,ans,a[N],b[N],st[N];

signed main(){
	n=read();
	int k=0;
	for (int i=1;i<=n;i++){
		b[i]=read();
		if (b[i]>b[k]) k=i;
	}
	for (int i=1;i<=n;i++) a[i]=b[(k+i-2)%n+1];
	ans=n-1;
	for (int i=1;i<=n;i++){
		while (top&&a[st[top]]<=a[i]) top--,ans++;
		st[++top]=i;
	}
	writeln(ans);
	return 0;
}

/*
5 3 1 2 4

2 2 2 2
*/


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define int long long
#define For(i,j,k) for(int i=(int)(j);i<=(int)(k);i++)
#define Rep(i,j,k) for(int i=(int)(j);i>=(int)(k);i--)
inline ll read(){
    ll x=0;char ch=getchar();bool f=0;
    for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=1;
    for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';
    return f?-x:x;
}
void write(ll x){
    if(x<0) putchar('-'),x=-x;
    if(x>=10) write(x/10);putchar(x%10+'0');
}
void writeln(ll x){write(x);puts("");}
void writep(ll x){write(x);putchar(' ');}

int const N=1e6+3;
int n,top,ans,a[N],b[N],st[N],l[N],r[N],f[N];

signed main(){
	n=read();
	int k=0;
	for (int i=1;i<=n;i++){
		b[i]=read();
		if (b[i]>b[k]) k=i;
	}
	for (int i=1;i<=n;i++) a[i]=b[(k+i-2)%n+1];
	for (int i=1;i<=n;i++) l[i]=1,r[i]=n+1;
	for (int i=1;i<=n;i++){
		while (top&&a[st[top]]<=a[i]) top--;
		if (top) l[i]=st[top];
		st[++top]=i;
	}
	top=0;
	for (int i=n;i;i--){
		while (top&&a[st[top]]<a[i]) top--;
		if (top) r[i]=st[top];
		st[++top]=i;
		if (r[i]<=n&&a[r[i]]==a[i]){
			f[i]=f[r[i]]+1;
			r[i]=r[r[i]];
		}
	}
	for (int i=2;i<=n;i++){
		ans+=f[i]+2;
		if (l[i]==1&&r[i]==n+1) ans--;
	}
	writeln(ans);
	return 0;
}

/*
5
5 3 1 2 4

4
2 2 2 2

3
2 2 2

4
2 2 3 3
*/


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define For(i,j,k) for(int i=(int)(j);i<=(int)(k);i++)
#define Rep(i,j,k) for(int i=(int)(j);i>=(int)(k);i--)
inline ll read(){
    ll x=0;char ch=getchar();bool f=0;
    for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=1;
    for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';
    return f?-x:x;
}
void write(ll x){
    if(x<0) putchar('-'),x=-x;
    if(x>=10) write(x/10);putchar(x%10+'0');
}
void writeln(ll x){write(x);puts("");}
void writep(ll x){write(x);putchar(' ');}

int const N=1e6+3;
int n,top,ans,a[N],b[N],st[N],l[N],r[N],f[N];

signed main(){
	n=read();
	int k=0;
	for (int i=1;i<=n;i++){
		b[i]=read();
		if (b[i]>=b[k]) k=i;
	}
	for (int i=1;i<=n;i++) a[i]=b[(k+i-2)%n+1];
	for (int i=1;i<=n;i++){
		while (top&&a[st[top]]<=a[i]) top--;
		l[i]=st[top];
		st[++top]=i;
	}
	top=0;
	for (int i=n;i;i--){
		while (top&&a[st[top]]<a[i]) top--;
		r[i]=st[top];
		st[++top]=i;
		while (r[i]<=n&&a[r[i]]==a[i]){
			f[i]=f[r[i]]+1;
			r[i]=r[r[i]];
		}
	}
	for (int i=2;i<=n;i++){
		ans+=f[i]+2;
		if (l[i]==1&&r[i]==0) ans--;
	}
	writeln(ans);
	return 0;
}

/*
5
5 3 1 2 4

4
2 2 2 2

3
2 2 2

4
2 2 3 3
*/


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define For(i,j,k) for(int i=(int)(j);i<=(int)(k);i++)
#define Rep(i,j,k) for(int i=(int)(j);i>=(int)(k);i--)
inline ll read(){
    ll x=0;char ch=getchar();bool f=0;
    for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=1;
    for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';
    return f?-x:x;
}
void write(ll x){
    if(x<0) putchar('-'),x=-x;
    if(x>=10) write(x/10);putchar(x%10+'0');
}
void writeln(ll x){write(x);puts("");}
void writep(ll x){write(x);putchar(' ');}

int const N=1e6+3;
int n,top,ans,a[N],b[N],st[N],l[N],r[N],f[N];

signed main(){
	n=read();
	int k=0;
	for (int i=1;i<=n;i++){
		b[i]=read();
		if (b[i]>b[k]) k=i;
	}
	for (int i=1;i<=n;i++) a[i]=b[(k+i-2)%n+1];
	for (int i=1;i<=n;i++) l[i]=1,r[i]=n+1;
	for (int i=1;i<=n;i++){
		while (top&&a[st[top]]<=a[i]) top--;
		if (top) l[i]=st[top];
		st[++top]=i;
	}
	top=0;
	for (int i=n;i;i--){
		while (top&&a[st[top]]<a[i]) top--;
		if (top) r[i]=st[top];
		st[++top]=i;
		if (r[i]<=n&&a[r[i]]==a[i]){
			f[i]=f[r[i]]+1;
			r[i]=r[r[i]];
		}
	}
	for (int i=2;i<=n;i++){
		ans+=f[i]+2;
		if (l[i]==1&&r[i]==n+1) ans--;
	}
	writeln(ans);
	return 0;
}

/*
5
5 3 1 2 4

4
2 2 2 2

3
2 2 2

4
2 2 3 3
*/


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define For(i,j,k) for(int i=(int)(j);i<=(int)(k);i++)
#define Rep(i,j,k) for(int i=(int)(j);i>=(int)(k);i--)
inline ll read(){
    ll x=0;char ch=getchar();bool f=0;
    for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=1;
    for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';
    return f?-x:x;
}
void write(ll x){
    if(x<0) putchar('-'),x=-x;
    if(x>=10) write(x/10);putchar(x%10+'0');
}
void writeln(ll x){write(x);puts("");}
void writep(ll x){write(x);putchar(' ');}

int const N=1e6+3;
int n,top,ans,a[N],b[N],st[N];

signed main(){
	n=read();
	int k=0;
	for (int i=1;i<=n;i++){
		b[i]=read();
		if (b[i]>b[k]) k=i;
	}
	for (int i=1;i<=n;i++) a[i]=b[(k+i-2)%n+1];
	for (int i=1;i<=n;i++){
		while (top&&a[st[top]]<a[i]) top--,ans++;
		if (i>1) ans++;
		int p=top-1;
		while (p>0&&a[st[p]]==a[i]) p--,ans++;
		st[++top]=i;
	}
	writeln(ans);
	return 0;
}

/*
5 3 1 2 4

2 2 2 2
*/


#include <iostream>
#include <cstdio>
#include <stack>
#define intg int
using namespace std;

intg n;
intg a[100005], b[100005], ca[100005], cb[100005], t[100005], ans;

struct node {
	intg x, t;
};

stack <node> s;

node opt(node tt, intg fl) {
	node tmp;
	while (!s.empty()) {
		tmp = s.top();
		if (fl == 1) {
			if (tmp.x == tt.x) t[tt.t] = t[tmp.t] + 1;
		}
		if (tmp.x <= tt.x) s.pop();
		else break;
	}
	if (s.empty()) tmp.x = tmp.t = 0;
	s.push(tt);
	return tmp;
}

int main() {
	scanf("%d", &n);
	for (int i = 1; i <= n; ++i) {
		scanf("%d", &a[i]);
	}
	intg mxn = 0, mxt;
	for (int i = 1; i <= n; ++i) {
		if (a[i] > mxn) mxn = a[i], mxt = i;
	}
	for (int i = 1; i <= n; ++i) {
		b[i] = a[(i + mxt - 2) % n + 1];
	}
	b[++n] = b[1];
	for (int i = 1; i < n; ++i) {
		node tmp = opt({b[i], i}, 1);
		ca[i] = tmp.t;
	}
	while (!s.empty()) s.pop();
	for (int i = n; i >= 1; --i) {
		node tmp = opt({b[i], i}, 0);
		cb[i] = tmp.t;
		if (i != n && i != 1) {
			if (ca[i] && cb[i]) ans += 2;
			ans += t[i];
			if (ca[i] == 1 && cb[i] == n) --ans;
		}
	}
	printf("%d\n", ans);
	return 0;
}


#include <iostream>
#include <cstdio>
#include <stack>
#define intg int
using namespace std;

intg n;
intg a[1000005], b[1000005], ca[1000005], cb[1000005], t[1000005], ans;

struct node {
	intg x, t;
};

stack <node> s;

node opt(node tt, intg fl) {
	node tmp;
	while (!s.empty()) {
		tmp = s.top();
		if (fl == 1) {
			if (tmp.x == tt.x) t[tt.t] = t[tmp.t] + 1;
		}
		if (tmp.x <= tt.x) s.pop();
		else break;
	}
	if (s.empty()) tmp.x = tmp.t = 0;
	s.push(tt);
	return tmp;
}

int main() {
	scanf("%d", &n);
	for (int i = 1; i <= n; ++i) {
		scanf("%d", &a[i]);
	}
	intg mxn = 0, mxt;
	for (int i = 1; i <= n; ++i) {
		if (a[i] > mxn) mxn = a[i], mxt = i;
	}
	for (int i = 1; i <= n; ++i) {
		b[i] = a[(i + mxt - 2) % n + 1];
	}
	b[++n] = b[1];
	for (int i = 1; i < n; ++i) {
		node tmp = opt({b[i], i}, 1);
		ca[i] = tmp.t;
	}
	while (!s.empty()) s.pop();
	for (int i = n; i >= 1; --i) {
		node tmp = opt({b[i], i}, 0);
		cb[i] = tmp.t;
		if (i != n && i != 1) {
			if (ca[i] && cb[i]) ans += 2;
			ans += t[i];
			if (ca[i] == 1 && cb[i] == n) --ans;
		}
	}
	printf("%d\n", ans);
	return 0;
}


#include <iostream>
#include <cstdio>
#include <stack>
#define intg long long
using namespace std;

intg n;
intg a[100005], b[100005], ca[100005], cb[100005], t[100005], ans;

struct node {
	intg x, t;
};

stack <node> s;

node opt(node tt, intg fl) {
	node tmp;
	while (!s.empty()) {
		tmp = s.top();
		if (fl == 1) {
			if (tmp.x == tt.x) t[tt.t] = t[tmp.t] + 1;
		}
		if (tmp.x <= tt.x) s.pop();
		else break;
	}
	if (s.empty()) tmp.x = tmp.t = 0;
	s.push(tt);
	return tmp;
}

int main() {
	scanf("%lld", &n);
	for (int i = 1; i <= n; ++i) {
		scanf("%lld", &a[i]);
	}
	intg mxn = 0, mxt;
	for (int i = 1; i <= n; ++i) {
		if (a[i] > mxn) mxn = a[i], mxt = i;
	}
	for (int i = 1; i <= n; ++i) {
		b[i] = a[(i + mxt - 2) % n + 1];
	}
	b[++n] = b[1];
	for (int i = 1; i < n; ++i) {
		node tmp = opt({b[i], i}, 1);
		ca[i] = tmp.t;
	}
	while (!s.empty()) s.pop();
	for (int i = n; i >= 1; --i) {
		node tmp = opt({b[i], i}, 0);
		cb[i] = tmp.t;
		if (i != n && i != 1) {
			if (ca[i] && cb[i]) ans += 2;
			ans += t[i];
			if (ca[i] == 1 && cb[i] == n) --ans;
		}
	}
	printf("%lld\n", ans);
	return 0;
}


#include <iostream>
#include <cstdio>
#include <stack>
#define intg int
using namespace std;

intg n;
intg a[100005], b[100005], ca[100005], cb[100005], t[100005], ans;

struct node {
	intg x, t;
};

stack <node> s;

node opt(node tt, intg fl) {
	node tmp;
	while (!s.empty()) {
		tmp = s.top();
		if (fl == 1) {
			if (tmp.x == tt.x) t[tt.t] = t[tmp.t] + 1;
		}
		if (tmp.x <= tt.x) s.pop();
		else break;
	}
	if (s.empty()) tmp.x = tmp.t = 0;
	s.push(tt);
	return tmp;
}

int main() {
	scanf("%d", &n);
	for (int i = 1; i <= n; ++i) {
		scanf("%d", &a[i]);
	}
	intg mxn = 0, mxt;
	for (int i = 1; i <= n; ++i) {
		if (a[i] > mxn) mxn = a[i], mxt = i;
	}
	for (int i = 1; i <= n; ++i) {
		b[i] = a[(i + mxt - 2) % n + 1];
	}
	b[++n] = b[1];
	for (int i = 1; i < n; ++i) {
		node tmp = opt({b[i], i}, 1);
		ca[i] = tmp.t;
	}
	while (!s.empty()) s.pop();
	for (int i = n; i >= 1; --i) {
		node tmp = opt({b[i], i}, 0);
		cb[i] = tmp.t;
		if (i != n && i != 1) {
			ans += (t[i] + 2);
			if (ca[i] == 1 && cb[i] == n) --ans;
		}
	}
	printf("%d\n", ans);
	return 0;
}


#include <iostream>
#include <cstdio>
#include <stack>
#define intg long long
using namespace std;

intg n;
intg a[1000005], b[1000005], ca[1000005], cb[1000005], t[1000005], ans;

struct node {
	intg x, t;
};

stack <node> s;

node opt(node tt, intg fl) {
	node tmp;
	while (!s.empty()) {
		tmp = s.top();
		if (fl == 1) {
			if (tmp.x == tt.x) t[tt.t] = t[tmp.t] + 1;
		}
		if (tmp.x <= tt.x) s.pop();
		else break;
	}
	if (s.empty()) tmp.x = tmp.t = 0;
	s.push(tt);
	return tmp;
}

int main() {
	scanf("%lld", &n);
	for (int i = 1; i <= n; ++i) {
		scanf("%lld", &a[i]);
	}
	intg mxn = 0, mxt;
	for (int i = 1; i <= n; ++i) {
		if (a[i] > mxn) mxn = a[i], mxt = i;
	}
	for (int i = 1; i <= n; ++i) {
		b[i] = a[(i + mxt - 2) % n + 1];
	}
	b[++n] = b[1];
	for (int i = 1; i < n; ++i) {
		node tmp = opt({b[i], i}, 1);
		ca[i] = tmp.t;
	}
	while (!s.empty()) s.pop();
	for (int i = n; i >= 1; --i) {
		node tmp = opt({b[i], i}, 0);
		cb[i] = tmp.t;
		if (i != n && i != 1) {
			if (ca[i] && cb[i]) ans += 2;
			ans += t[i];
			if (ca[i] == 1 && cb[i] == n) --ans;
		}
	}
	printf("%lld\n", ans);
	return 0;
}


#include <bits/stdc++.h>

#define fly(...) fprintf(stderr, __VA_ARGS__)

const int maxn = 1000005;

int n, a[maxn];
int L[maxn];
int R[maxn];
int cnt[maxn];

int main()
{
    scanf("%d", &n);
    for(int i = 0; i < n; ++i)
        scanf("%d", &a[i]);

    std::rotate(a, std::max_element(a, a + n), a + n);
    a[n] = a[0];

    for(int i = 1; i <= n; ++i)
    {
        L[i] = i - 1;
        while(L[i] > 0 && a[i] >= a[L[i]]) L[i] = L[L[i]];
    }
    for(int i = n - 1; i >= 0; --i)
    {
        R[i] = i + 1;
        while(R[i] < n && a[i] > a[R[i]]) R[i] = R[R[i]];
        if(R[i] < n && a[i] == a[R[i]])
        {
            cnt[i] = cnt[R[i]] + 1;
            R[i] = R[R[i]];
        }
    }

    long long ans = 0;
    for(int i = 1; i < n; ++i)
    {
        ans += cnt[i] + 2;
        ans -= (L[i] == 0 && R[i] == n);
    }
    std::cout << ans << std::endl;

    return 0;
}


#include <bits/stdc++.h>

#define fly(...) fprintf(stderr, __VA_ARGS__)

const int maxn = 1000005;

int n, a[maxn];
int s[maxn], top;
int L[maxn], R[maxn];

int main()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; ++i)
        scanf("%d", &a[i]);

    std::rotate(a + 1, std::max_element(a + 1, a + n + 1), a + n + 1);

    s[++top] = 1;
    for(int i = 1; i <= n; ++i)
    {
        while(top && a[s[top]] < a[i]) R[s[top--]] = i - 1;
        s[++top] = i;
    }
    while(top) R[s[top--]] = n;

    s[++top] = n;
    for(int i = n; i >= 1; --i)
    {
        while(top && a[s[top]] < a[i]) L[s[top--]] = i + 1;
        s[++top] = i;
    }
    while(top) L[s[top--]] = 1;

    long long ans = 0;
    for(int i = 1; i <= n; ++i)
        ans += (i - L[i] + 1) * (R[i] - i + 1) - (L[i] == R[i]);
    std::cout << ans / 2 << std::endl;

    return 0;
}


#include <bits/stdc++.h>

#define fly(...) fprintf(stderr, __VA_ARGS__)

const int maxn = 1000005;

int n, a[maxn];
int L[maxn];
int R[maxn];
int cnt[maxn];

int main()
{
	scanf("%d", &n);
	for(int i = 0; i < n; ++i)
		scanf("%d", &a[i]);

	std::rotate(a, std::max_element(a, a + n), a + n);
	a[n] = a[0];

	for(int i = 1; i <= n; ++i)
	{
		L[i] = i - 1;
		while(L[i] > 0 && a[i] > a[L[i]]) L[i] = L[L[i]];
	}
	for(int i = n - 1; i >= 0; --i)
	{
		R[i] = i + 1;
		while(R[i] < n && a[i] > a[R[i]]) R[i] = R[R[i]];
		if(R[i] < n && a[i] == a[R[i]])
		{
			cnt[i] = cnt[R[i]] + 1;
			R[i] = R[R[i]];
		}
	}

	long long ans = 0;
	for(int i = 1; i < n; ++i)
	{
		ans += cnt[i] + 2;
		ans -= (L[i] == 0 && R[i] == n);
	}
	std::cout << ans << std::endl;

	return 0;
}


#include <bits/stdc++.h>

#define fly(...) fprintf(stderr, __VA_ARGS__)

const int maxn = 1000005;

int n, a[maxn];
int s[maxn], top;
int L[maxn], R[maxn];

int main()
{
//	freopen("input.txt", "r", stdin);

	scanf("%d", &n);
	for(int i = 1; i <= n; ++i)
		scanf("%d", &a[i]);

	std::rotate(a + 1, std::max_element(a + 1, a + n + 1), a + n + 1);

//	for(int i = 1; i <= n; ++i)
//		fly("%d ", a[i]);
//	fly("\n");

	s[++top] = 1;
	for(int i = 1; i <= n; ++i)
	{
		while(top && a[s[top]] < a[i]) R[s[top--]] = i - 1;
		s[++top] = i;
	}
	while(top) R[s[top--]] = n;

	s[++top] = n;
	for(int i = n; i >= 1; --i)
	{
		while(top && a[s[top]] < a[i]) L[s[top--]] = i + 1;
		s[++top] = i;
	}
	while(top) L[s[top--]] = 1;

	long long ans = 0;
	for(int i = 1; i <= n; ++i)
		ans += (i - L[i] + 1) * (R[i] - i + 1);
	std::cout << ans / 2 << std::endl;

	return 0;
}


#include<bits/stdc++.h>

#define ll long long
#define INF 2147483647

int inp(){
    char c =getchar();
    while(c < '0' || c > '9')
        c = getchar();
    int sum = 0;
    while(c >= '0' && c <= '9'){
        sum = sum * 10 + c - '0';
        c = getchar();
    }
    return sum;
}

int st[1000010];
std::pair<int, int> s[1000010];
int a[1000010];
bool flg[1000010];

int main(){
    int n = inp();
    int max = 0;
    int pos;
    for(int i = 1; i <= n; i++){
        a[i] = inp();
        max = std::max(max, a[i]);
        if(a[i] == max)
            pos = i;
    }
    memcpy(st, a, sizeof(a));
    for(int i = pos; i <= n; i++)
        a[i - pos + 1] = st[i];
    for(int i = 1; i < pos; i++)
        a[n - pos + i + 1] = st[i];
    for(int i = 1; i <= n; i++)
        printf("a[%d] = %d\n", i, a[i]);
    int top = 0;
    ll ans = 0;
    for(int i = 2; i <= n; i++){
        while(top && s[top].first < a[i])
            ans += s[top--].second;
        if(s[top].first == a[i]){
            ans += s[top].second;
            if(top > 1)
                ans++;
            s[top].second++;
        } else {
            ans++;
            s[++top] = std::make_pair(a[i], 1);
        }
    }
    max = 0;
    for(int i = 2; i <= n; i++){
        max = std::max(max, a[i]);
        if(a[i] == max)
            flg[i] = true;
    }
    max = 0;
    for(int i = n; i >= 2; i--){
        max = std::max(max, a[i]);
        if(a[i] == max && !flg[i])
            ans++;
    }
    printf("%lld\n", ans);
}


#include<bits/stdc++.h>

#define ll long long
#define INF 2147483647

int inp(){
    char c =getchar();
    while(c < '0' || c > '9')
        c = getchar();
    int sum = 0;
    while(c >= '0' && c <= '9'){
        sum = sum * 10 + c - '0';
        c = getchar();
    }
    return sum;
}

int st[1000010];
std::pair<int, int> s[1000010];
int a[1000010];
bool flg[1000010];

int main(){
    int n = inp();
    int max = 0;
    int pos;
    for(int i = 1; i <= n; i++){
        a[i] = inp();
        max = std::max(max, a[i]);
        if(a[i] == max)
            pos = i;
    }
    memcpy(st, a, sizeof(a));
    for(int i = pos; i <= n; i++)
        a[i - pos + 1] = st[i];
    for(int i = 1; i < pos; i++)
        a[n - pos + i + 1] = st[i];
    // for(int i = 1; i <= n; i++)
    //     printf("a[%d] = %d\n", i, a[i]);
    int top = 0;
    ll ans = 0;
    for(int i = 2; i <= n; i++){
        while(top && s[top].first < a[i])
            ans += s[top--].second;
        if(s[top].first == a[i]){
            ans += s[top].second;
            if(top > 1)
                ans++;
            s[top].second++;
        } else {
            ans++;
            s[++top] = std::make_pair(a[i], 1);
        }
    }
    max = 0;
    for(int i = 2; i <= n; i++){
        max = std::max(max, a[i]);
        if(a[i] == max)
            flg[i] = true;
    }
    max = 0;
    for(int i = n; i >= 2; i--){
        max = std::max(max, a[i]);
        if(a[i] == max && !flg[i])
            ans++;
    }
    printf("%lld\n", ans);
}


#include<bits/stdc++.h>

#define ll long long
#define INF 2147483647

int inp(){
    char c =getchar();
    while(c < '0' || c > '9')
        c = getchar();
    int sum = 0;
    while(c >= '0' && c <= '9'){
        sum = sum * 10 + c - '0';
        c = getchar();
    }
    return sum;
}

int st[1000010];
std::pair<int, int> s[1000010];
int a[1000010];
bool flg[1000010];

int main(){
    int n = inp();
    int max = 0;
    int pos;
    for(int i = 1; i <= n; i++){
        a[i] = inp();
        max = std::max(max, a[i]);
        if(a[i] == max)
            pos = i;
    }
    memcpy(st, a, sizeof(a));
    for(int i = pos; i <= n; i++)
        a[i - pos + 1] = st[i];
    for(int i = 1; i < pos; i++)
        a[n - pos + i + 1] = st[i];
    int top = 0;
    ll ans = 0;
    for(int i = 1; i <= n; i++){
        while(top && s[top].first < a[i])
            ans += s[top--].second;
        if(s[top].first == a[i]){
            ans += s[top].second;
            if(top > 1)
                ans++;
            s[top].second++;
        } else {
            ans++;
            s[++top] = std::make_pair(a[i], 1);
        }
    }
    max = 0;
    for(int i = 2; i <= n; i++){
        max = std::max(max, a[i]);
        if(a[i] == max)
            flg[i] = true;
    }
    max = 0;
    for(int i = n; i >= 2; i--){
        max = std::max(max, a[i]);
        if(a[i] == max && !flg[i])
            ans++;
    }
    printf("%lld\n", ans - 1);
}


#include<bits/stdc++.h>

#define ll long long
#define INF 2147483647

int inp(){
    char c =getchar();
    while(c < '0' || c > '9')
        c = getchar();
    int sum = 0;
    while(c >= '0' && c <= '9'){
        sum = sum * 10 + c - '0';
        c = getchar();
    }
    return sum;
}

int st[1000010];
std::pair<int, int> s[1000010];
int a[1000010];
bool flg[1000010];

int main(){
    int n = inp();
    int max = 0;
    int pos;
    for(int i = 1; i <= n; i++){
        a[i] = inp();
        max = std::max(max, a[i]);
        if(a[i] == max)
            pos = i;
    }
    memcpy(st, a, sizeof(a));
    for(int i = pos; i <= n; i++)
        a[i - pos + 1] = st[i];
    for(int i = 1; i < pos; i++)
        a[n - pos + i + 1] = st[i];
    // for(int i = 1; i <= n; i++)
    //     printf("a[%d] = %d\n", i, a[i]);
    int top = 0;
    ll ans = 0;
    for(int i = 1; i <= n; i++){
        while(top && s[top].first < a[i])
            ans += s[top--].second;
        if(s[top].first == a[i]){
            ans += s[top].second;
            if(top > 1)
                ans++;
            s[top].second++;
        } else {
            ans++;
            s[++top] = std::make_pair(a[i], 1);
        }
    }
    max = 0;
    for(int i = 2; i <= n; i++){
        max = std::max(max, a[i]);
        if(a[i] == max)
            flg[i] = true;
    }
    max = 0;
    for(int i = n; i >= 2; i--){
        max = std::max(max, a[i]);
        if(a[i] == max && !flg[i])
            ans++;
    }
    printf("%lld\n", ans - 1);
}


//This program is written by Brian Peng.
#pragma GCC optimize("Ofast","inline","no-stack-protector")
#include<bits/stdc++.h>
using namespace std;
#define Rd(a) (a=read())
#define Gc(a) (a=getchar())
#define Pc(a) putchar(a)
int read(){
	register int x;register char c(getchar());register bool k;
	while(!isdigit(c)&&c^'-')if(Gc(c)==EOF)exit(0);
	if(c^'-')k=1,x=c&15;else k=x=0;
	while(isdigit(Gc(c)))x=(x<<1)+(x<<3)+(c&15);
	return k?x:-x;
}
void wr(register int a){
	if(a<0)Pc('-'),a=-a;
	if(a<=9)Pc(a|'0');
	else wr(a/10),Pc((a%10)|'0');
}
signed const INF(0x3f3f3f3f),NINF(0xc3c3c3c3);
long long const LINF(0x3f3f3f3f3f3f3f3fLL),LNINF(0xc3c3c3c3c3c3c3c3LL);
#define Ps Pc(' ')
#define Pe Pc('\n')
#define Frn0(i,a,b) for(register int i(a);i<(b);++i)
#define Frn1(i,a,b) for(register int i(a);i<=(b);++i)
#define Frn_(i,a,b) for(register int i(a);i>=(b);--i)
#define Mst(a,b) memset(a,b,sizeof(a))
#define File(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout)
#define N (1000010)
int n,h[N]{INF},s[N],tp,l[N],m,b[N],b2[N],ans,cnt;
struct D{int a,i,b;}d[N];
vector<int>q[N];
signed main(){
	h[Rd(n)<<1|1]=INF;
	Frn1(i,1,n)d[i]={read(),i};
	sort(d+1,d+n+1,[](D a,D b){return a.a<b.a;});
	Frn1(i,1,n)d[i].b=d[i].a>d[i-1].a?++m:m;
	sort(d+1,d+n+1,[](D a,D b){return a.i<b.i;});
	Frn1(i,1,n)if((h[i+n]=h[i]=d[i].b)==m)++cnt;
	Frn1(i,1,n<<1){
		while(h[i]>=h[s[tp]])--tp;
		l[i]=s[tp],s[++tp]=i;
		if(i>n&&l[i]>i-n)++ans;
	}
	s[tp=0]=n<<1|1;
	Frn_(i,n<<1,1){
		++b[h[i]];
		while(h[i]>=h[s[tp]])--tp;
		if(i<=n){
			if(s[tp]<i+n)++ans;
			ans+=b[h[i]]-1,q[min(i+n,s[tp])-1].push_back(i);
		}
		s[++tp]=i;
	}
	Frn1(i,1,n<<1){
		++b2[h[i]];
		for(int j:q[i])ans+=b2[h[j]]-b[h[j]];
	}
	if(cnt==1){
		cnt=0;
		Frn1(i,1,n)if(h[i]==m-1)++cnt;
		ans-=cnt;
	}else ans-=(cnt*(cnt-1))>>1;
	wr(ans),exit(0);
}


//This program is written by Brian Peng.
#pragma GCC optimize("Ofast","inline","no-stack-protector")
#include<bits/stdc++.h>
using namespace std;
#define Rd(a) (a=read())
#define Gc(a) (a=getchar())
#define Pc(a) putchar(a)
int read(){
	register int x;register char c(getchar());register bool k;
	while(!isdigit(c)&&c^'-')if(Gc(c)==EOF)exit(0);
	if(c^'-')k=1,x=c&15;else k=x=0;
	while(isdigit(Gc(c)))x=(x<<1)+(x<<3)+(c&15);
	return k?x:-x;
}
void wr(register int a){
	if(a<0)Pc('-'),a=-a;
	if(a<=9)Pc(a|'0');
	else wr(a/10),Pc((a%10)|'0');
}
signed const INF(0x3f3f3f3f),NINF(0xc3c3c3c3);
long long const LINF(0x3f3f3f3f3f3f3f3fLL),LNINF(0xc3c3c3c3c3c3c3c3LL);
#define Ps Pc(' ')
#define Pe Pc('\n')
#define Frn0(i,a,b) for(register int i(a);i<(b);++i)
#define Frn1(i,a,b) for(register int i(a);i<=(b);++i)
#define Frn_(i,a,b) for(register int i(a);i>=(b);--i)
#define Mst(a,b) memset(a,b,sizeof(a))
#define File(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout)
#define N (1000010)
#define M ((l+r)>>1)
int n,h[N]{INF},rt[N],sz,s[N],tp,mx,mx2;
long long ans,cnt;
struct{int ls,rs,v;}t[N<<4];
int mdf(int u,int l,int r,int k);
int qry(int u,int v,int l,int r,int k);
signed main(){
	h[Rd(n)<<1|1]=INF;
	Frn1(i,1,n)(h[i+n]=Rd(h[i]))>mx?(mx=h[i],cnt=1):h[i]==mx?++cnt:0;
	Frn1(i,1,n<<1){
		while(h[i]>=h[s[tp]])--tp;
		rt[i]=mdf(rt[i-1],0,n<<1,s[tp]);
		s[++tp]=i;
	}
	s[tp=0]=n<<1|1;
	Frn_(i,n<<1,1){
		while(h[i]>=h[s[tp]])--tp;
		if(i<=n){
			if(s[tp]<i+n)++ans;
			ans+=qry(rt[i],rt[min(s[tp],i+n)-1],0,n<<1,i);
		}
		s[++tp]=i;
	}
	if(cnt==1){
		cnt=0;
		Frn1(i,1,n)if(h[i]<mx)h[i]>mx2?(mx2=h[i],cnt=1):h[i]==mx2?++cnt:0;
		ans-=cnt;
	}else ans-=(cnt*(cnt-1))>>1;
	wr(ans),exit(0);
}
int mdf(int u,int l,int r,int k){
	int re(++sz);t[re]=t[u];
	if(l==r){++t[re].v;return re;}
	k<=M?t[re].ls=mdf(t[u].ls,l,M,k):t[re].rs=mdf(t[u].rs,M+1,r,k);
	t[re].v=t[t[re].ls].v+t[t[re].rs].v;
	return re;
}
int qry(int u,int v,int l,int r,int k){
	if(r<=k)return t[v].v-t[u].v;
	if(l>k||t[u].v==t[v].v)return 0;
	return qry(t[u].ls,t[v].ls,l,M,k)+qry(t[u].rs,t[v].rs,M+1,r,k);
}


//This program is written by Brian Peng.
#pragma GCC optimize("Ofast","inline","no-stack-protector")
#include<bits/stdc++.h>
using namespace std;
#define Rd(a) (a=read())
#define Gc(a) (a=getchar())
#define Pc(a) putchar(a)
int read(){
	register int x;register char c(getchar());register bool k;
	while(!isdigit(c)&&c^'-')if(Gc(c)==EOF)exit(0);
	if(c^'-')k=1,x=c&15;else k=x=0;
	while(isdigit(Gc(c)))x=(x<<1)+(x<<3)+(c&15);
	return k?x:-x;
}
void wr(register long long a){
	if(a<0)Pc('-'),a=-a;
	if(a<=9)Pc(a|'0');
	else wr(a/10),Pc((a%10)|'0');
}
signed const INF(0x3f3f3f3f),NINF(0xc3c3c3c3);
long long const LINF(0x3f3f3f3f3f3f3f3fLL),LNINF(0xc3c3c3c3c3c3c3c3LL);
#define Ps Pc(' ')
#define Pe Pc('\n')
#define Frn0(i,a,b) for(register int i(a);i<(b);++i)
#define Frn1(i,a,b) for(register int i(a);i<=(b);++i)
#define Frn_(i,a,b) for(register int i(a);i>=(b);--i)
#define Mst(a,b) memset(a,b,sizeof(a))
#define File(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout)
#define N (2000010)
int n,h[N]{INF},s[N],tp,l[N],mx,mx2;
long long ans,cnt;
vector<int>q[N];
unordered_map<int,int>b,b2;
signed main(){
	File("A");
	h[Rd(n)<<1|1]=INF;
	Frn1(i,1,n)h[i+n]=Rd(h[i]);
	Frn1(i,1,n<<1){
		while(h[i]>=h[s[tp]])--tp;
		l[i]=s[tp],s[++tp]=i;
		if(i>n&&l[i]>i-n)++ans;
	}
	s[tp=0]=n<<1|1;
	Frn_(i,n<<1,1){
		++b[h[i]];
		while(h[i]>=h[s[tp]])--tp;
		if(i<=n){
			if(s[tp]<i+n)++ans;
			ans+=b[h[i]]-1,q[min(i+n,s[tp])-1].push_back(i);
		}
		s[++tp]=i;
	}
	Frn1(i,1,n<<1){
		++b2[h[i]];
		for(int j:q[i])ans+=b2[h[j]]-b[h[j]];
	}
	Frn1(i,1,n)h[i]>mx?(mx=h[i],cnt=1):h[i]==mx?++cnt:0;
	if(cnt==1){
		cnt=0;
		Frn1(i,1,n)if(h[i]<mx)h[i]>mx2?(mx2=h[i],cnt=1):h[i]==mx2?++cnt:0;
		ans-=cnt;
	}else ans-=(cnt*(cnt-1))>>1;
	wr(ans),exit(0);
}


//This program is written by Brian Peng.
#pragma GCC optimize("Ofast","inline","no-stack-protector")
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define Rd(a) (a=read())
#define Gc(a) (a=getchar())
#define Pc(a) putchar(a)
int read(){
	register int x;register char c(getchar());register bool k;
	while(!isdigit(c)&&c^'-')if(Gc(c)==EOF)exit(0);
	if(c^'-')k=1,x=c&15;else k=x=0;
	while(isdigit(Gc(c)))x=(x<<1)+(x<<3)+(c&15);
	return k?x:-x;
}
void wr(register int a){
	if(a<0)Pc('-'),a=-a;
	if(a<=9)Pc(a|'0');
	else wr(a/10),Pc((a%10)|'0');
}
signed const INF(0x3f3f3f3f),NINF(0xc3c3c3c3);
long long const LINF(0x3f3f3f3f3f3f3f3fLL),LNINF(0xc3c3c3c3c3c3c3c3LL);
#define Ps Pc(' ')
#define Pe Pc('\n')
#define Frn0(i,a,b) for(register int i(a);i<(b);++i)
#define Frn1(i,a,b) for(register int i(a);i<=(b);++i)
#define Frn_(i,a,b) for(register int i(a);i>=(b);--i)
#define Mst(a,b) memset(a,b,sizeof(a))
#define File(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout)
#define N (1000010)
#define M ((l+r)>>1)
int n,h[N]{INF},rt[N],sz,s[N],tp,ans,mx,cnt,mx2;
struct{int ls,rs,v;}t[N<<5];
int mdf(int u,int l,int r,int k);
int qry(int u,int v,int l,int r,int k);
signed main(){
	h[Rd(n)<<1|1]=INF;
	Frn1(i,1,n)(h[i+n]=Rd(h[i]))>mx?(mx=h[i],cnt=1):h[i]==mx?++cnt:0;
	Frn1(i,1,n<<1){
		while(h[i]>=h[s[tp]])--tp;
		rt[i]=mdf(rt[i-1],0,n<<1,s[tp]);
		s[++tp]=i;
	}
	s[tp=0]=n<<1|1;
	Frn_(i,n<<1,1){
		while(h[i]>=h[s[tp]])--tp;
		if(i<=n){
			if(s[tp]<i+n)++ans;
			ans+=qry(rt[i],rt[min(s[tp],i+n)-1],1,n<<1,i);
		}
		s[++tp]=i;
	}
	if(cnt==1){
		cnt=0;
		Frn1(i,1,n)if(h[i]<mx)h[i]>mx2?(mx2=h[i],cnt=1):h[i]==mx2?++cnt:0;
		ans-=cnt;
	}else ans-=(cnt*(cnt-1))>>1;
	wr(ans),exit(0);
}
int mdf(int u,int l,int r,int k){
	int re(++sz);t[re]=t[u];
	if(l==r){++t[re].v;return re;}
	k<=M?t[re].ls=mdf(t[u].ls,l,M,k):t[re].rs=mdf(t[u].rs,M+1,r,k);
	t[re].v=t[t[re].ls].v+t[t[re].rs].v;
	return re;
}
int qry(int u,int v,int l,int r,int k){
	if(r<=k)return t[v].v-t[u].v;
	if(l>k||t[u].v==t[v].v)return 0;
	return qry(t[u].ls,t[v].ls,l,M,k)+qry(t[u].rs,t[v].rs,M+1,r,k);
}


//This program is written by Brian Peng.
#pragma GCC optimize("Ofast","inline","no-stack-protector")
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define Rd(a) (a=read())
#define Gc(a) (a=getchar())
#define Pc(a) putchar(a)
int read(){
	register int x;register char c(getchar());register bool k;
	while(!isdigit(c)&&c^'-')if(Gc(c)==EOF)exit(0);
	if(c^'-')k=1,x=c&15;else k=x=0;
	while(isdigit(Gc(c)))x=(x<<1)+(x<<3)+(c&15);
	return k?x:-x;
}
void wr(register int a){
	if(a<0)Pc('-'),a=-a;
	if(a<=9)Pc(a|'0');
	else wr(a/10),Pc((a%10)|'0');
}
signed const INF(0x3f3f3f3f),NINF(0xc3c3c3c3);
long long const LINF(0x3f3f3f3f3f3f3f3fLL),LNINF(0xc3c3c3c3c3c3c3c3LL);
#define Ps Pc(' ')
#define Pe Pc('\n')
#define Frn0(i,a,b) for(register int i(a);i<(b);++i)
#define Frn1(i,a,b) for(register int i(a);i<=(b);++i)
#define Frn_(i,a,b) for(register int i(a);i>=(b);--i)
#define Mst(a,b) memset(a,b,sizeof(a))
#define File(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout)
#define N (1000010)
#define M ((l+r)>>1)
int n,h[N]{INF},rt[N],sz,s[N],tp,ans,mx,cnt,mx2;
struct{int ls,rs,v;}t[N<<3];
int mdf(int u,int l,int r,int k);
int qry(int u,int v,int l,int r,int k);
signed main(){
	h[Rd(n)<<1|1]=INF;
	Frn1(i,1,n)(h[i+n]=Rd(h[i]))>mx?(mx=h[i],cnt=1):h[i]==mx?++cnt:0;
	Frn1(i,1,n<<1){
		while(h[i]>=h[s[tp]])--tp;
		rt[i]=mdf(rt[i-1],0,n<<1,s[tp]);
		s[++tp]=i;
	}
	s[tp=0]=n<<1|1;
	Frn_(i,n<<1,1){
		while(h[i]>=h[s[tp]])--tp;
		if(i<=n){
			if(s[tp]<i+n)++ans;
			ans+=qry(rt[i],rt[min(s[tp],i+n)-1],0,n<<1,i);
		}
		s[++tp]=i;
	}
	if(cnt==1){
		cnt=0;
		Frn1(i,1,n)if(h[i]<mx)h[i]>mx2?(mx2=h[i],cnt=1):h[i]==mx2?++cnt:0;
		ans-=cnt;
	}else ans-=(cnt*(cnt-1))>>1;
	wr(ans),exit(0);
}
int mdf(int u,int l,int r,int k){
	int re(++sz);t[re]=t[u];
	if(l==r){++t[re].v;return re;}
	k<=M?t[re].ls=mdf(t[u].ls,l,M,k):t[re].rs=mdf(t[u].rs,M+1,r,k);
	t[re].v=t[t[re].ls].v+t[t[re].rs].v;
	return re;
}
int qry(int u,int v,int l,int r,int k){
	if(r<=k)return t[v].v-t[u].v;
	if(l>k||t[u].v==t[v].v)return 0;
	return qry(t[u].ls,t[v].ls,l,M,k)+qry(t[u].rs,t[v].rs,M+1,r,k);
}


//This program is written by Brian Peng.
#pragma GCC optimize("Ofast","inline","no-stack-protector")
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define Rd(a) (a=read())
#define Gc(a) (a=getchar())
#define Pc(a) putchar(a)
int read(){
	register int x;register char c(getchar());register bool k;
	while(!isdigit(c)&&c^'-')if(Gc(c)==EOF)exit(0);
	if(c^'-')k=1,x=c&15;else k=x=0;
	while(isdigit(Gc(c)))x=(x<<1)+(x<<3)+(c&15);
	return k?x:-x;
}
void wr(register int a){
	if(a<0)Pc('-'),a=-a;
	if(a<=9)Pc(a|'0');
	else wr(a/10),Pc((a%10)|'0');
}
signed const INF(0x3f3f3f3f),NINF(0xc3c3c3c3);
long long const LINF(0x3f3f3f3f3f3f3f3fLL),LNINF(0xc3c3c3c3c3c3c3c3LL);
#define Ps Pc(' ')
#define Pe Pc('\n')
#define Frn0(i,a,b) for(register int i(a);i<(b);++i)
#define Frn1(i,a,b) for(register int i(a);i<=(b);++i)
#define Frn_(i,a,b) for(register int i(a);i>=(b);--i)
#define Mst(a,b) memset(a,b,sizeof(a))
#define File(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout)
#define N (2000010)
int n,h[N]{INF},d[N],s[N],tp,l[N],m,b[N],b2[N],ans,cnt;
vector<int>q[N];
signed main(){
	h[Rd(n)<<1|1]=INF;
	Frn1(i,1,n)d[i]=Rd(h[i]);
	sort(d+1,d+n+1),m=unique(d+1,d+n+1)-d-1;
	Frn1(i,1,n)if((h[i+n]=h[i]=lower_bound(d+1,d+m+1,h[i])-d)==m)++cnt;
	Frn1(i,1,n<<1){
		while(h[i]>=h[s[tp]])--tp;
		l[i]=s[tp],s[++tp]=i;
		if(i>n&&l[i]>i-n)++ans;
	}
	s[tp=0]=n<<1|1;
	Frn_(i,n<<1,1){
		++b[h[i]];
		while(h[i]>=h[s[tp]])--tp;
		if(i<=n){
			if(s[tp]<i+n)++ans;
			ans+=b[h[i]]-1,q[min(i+n,s[tp])-1].push_back(i);
		}
		s[++tp]=i;
	}
	Frn1(i,1,n<<1){
		++b2[h[i]];
		for(int j:q[i])ans+=b2[h[j]]-b[h[j]];
	}
	if(cnt==1){
		cnt=0;
		Frn1(i,1,n)if(h[i]==m-1)++cnt;
		ans-=cnt;
	}else ans-=(cnt*(cnt-1))>>1;
	wr(ans),exit(0);
}


//This program is written by Brian Peng.
#pragma GCC optimize("Ofast","inline","no-stack-protector")
#include<bits/stdc++.h>
using namespace std;
#define Rd(a) (a=read())
#define Gc(a) (a=getchar())
#define Pc(a) putchar(a)
int read(){
	register int x;register char c(getchar());register bool k;
	while(!isdigit(c)&&c^'-')if(Gc(c)==EOF)exit(0);
	if(c^'-')k=1,x=c&15;else k=x=0;
	while(isdigit(Gc(c)))x=(x<<1)+(x<<3)+(c&15);
	return k?x:-x;
}
void wr(register long long a){
	if(a<0)Pc('-'),a=-a;
	if(a<=9)Pc(a|'0');
	else wr(a/10),Pc((a%10)|'0');
}
signed const INF(0x3f3f3f3f),NINF(0xc3c3c3c3);
long long const LINF(0x3f3f3f3f3f3f3f3fLL),LNINF(0xc3c3c3c3c3c3c3c3LL);
#define Ps Pc(' ')
#define Pe Pc('\n')
#define Frn0(i,a,b) for(register int i(a);i<(b);++i)
#define Frn1(i,a,b) for(register int i(a);i<=(b);++i)
#define Frn_(i,a,b) for(register int i(a);i>=(b);--i)
#define Mst(a,b) memset(a,b,sizeof(a))
#define File(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout)
#define N (2000010)
int n,h[N]{INF},s[N],tp,l[N],mx,mx2;
long long ans,cnt;
vector<int>q[N];
unordered_map<int,int>b,b2;
signed main(){
	h[Rd(n)<<1|1]=INF;
	Frn1(i,1,n)h[i+n]=Rd(h[i]);
	Frn1(i,1,n<<1){
		while(h[i]>=h[s[tp]])--tp;
		l[i]=s[tp],s[++tp]=i;
		if(i>n&&l[i]>i-n)++ans;
	}
	s[tp=0]=n<<1|1;
	Frn_(i,n<<1,1){
		++b[h[i]];
		while(h[i]>=h[s[tp]])--tp;
		if(i<=n){
			if(s[tp]<i+n)++ans;
			ans+=b[h[i]]-1,q[min(i+n,s[tp])-1].push_back(i);
		}
		s[++tp]=i;
	}
	Frn1(i,1,n<<1){
		++b2[h[i]];
		for(int j:q[i])ans+=b2[h[j]]-b[h[j]];
	}
	Frn1(i,1,n)h[i]>mx?(mx=h[i],cnt=1):h[i]==mx?++cnt:0;
	if(cnt==1){
		cnt=0;
		Frn1(i,1,n)if(h[i]<mx)h[i]>mx2?(mx2=h[i],cnt=1):h[i]==mx2?++cnt:0;
		ans-=cnt;
	}else ans-=(cnt*(cnt-1))>>1;
	wr(ans),exit(0);
}


//This program is written by Brian Peng.
#pragma GCC optimize("Ofast","inline","no-stack-protector")
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define Rd(a) (a=read())
#define Gc(a) (a=getchar())
#define Pc(a) putchar(a)
int read(){
	register int x;register char c(getchar());register bool k;
	while(!isdigit(c)&&c^'-')if(Gc(c)==EOF)exit(0);
	if(c^'-')k=1,x=c&15;else k=x=0;
	while(isdigit(Gc(c)))x=(x<<1)+(x<<3)+(c&15);
	return k?x:-x;
}
void wr(register int a){
	if(a<0)Pc('-'),a=-a;
	if(a<=9)Pc(a|'0');
	else wr(a/10),Pc((a%10)|'0');
}
signed const INF(0x3f3f3f3f),NINF(0xc3c3c3c3);
long long const LINF(0x3f3f3f3f3f3f3f3fLL),LNINF(0xc3c3c3c3c3c3c3c3LL);
#define Ps Pc(' ')
#define Pe Pc('\n')
#define Frn0(i,a,b) for(register int i(a);i<(b);++i)
#define Frn1(i,a,b) for(register int i(a);i<=(b);++i)
#define Frn_(i,a,b) for(register int i(a);i>=(b);--i)
#define Mst(a,b) memset(a,b,sizeof(a))
#define File(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout)
#define N (1000010)
#define M ((l+r)>>1)
int n,h[N]{INF},rt[N],sz,s[N],tp,ans,mx,cnt,mx2;
struct{int ls,rs,v;}t[N<<4];
int mdf(int u,int l,int r,int k);
int qry(int u,int v,int l,int r,int k);
signed main(){
	h[Rd(n)<<1|1]=INF;
	Frn1(i,1,n)(h[i+n]=Rd(h[i]))>mx?(mx=h[i],cnt=1):h[i]==mx?++cnt:0;
	Frn1(i,1,n<<1){
		while(h[i]>=h[s[tp]])--tp;
		rt[i]=mdf(rt[i-1],0,n<<1,s[tp]);
		s[++tp]=i;
	}
	s[tp=0]=n<<1|1;
	Frn_(i,n<<1,1){
		while(h[i]>=h[s[tp]])--tp;
		if(i<=n){
			if(s[tp]<i+n)++ans;
			ans+=qry(rt[i],rt[min(s[tp],i+n)-1],1,n<<1,i);
		}
		s[++tp]=i;
	}
	if(cnt==1){
		cnt=0;
		Frn1(i,1,n)if(h[i]<mx)h[i]>mx2?(mx2=h[i],cnt=1):h[i]==mx2?++cnt:0;
		ans-=cnt;
	}else ans-=(cnt*(cnt-1))>>1;
	wr(ans),exit(0);
}
int mdf(int u,int l,int r,int k){
	int re(++sz);t[re]=t[u];
	if(l==r){++t[re].v;return re;}
	k<=M?t[re].ls=mdf(t[u].ls,l,M,k):t[re].rs=mdf(t[u].rs,M+1,r,k);
	t[re].v=t[t[re].ls].v+t[t[re].rs].v;
	return re;
}
int qry(int u,int v,int l,int r,int k){
	if(r<=k)return t[v].v-t[u].v;
	if(l>k||t[u].v==t[v].v)return 0;
	return qry(t[u].ls,t[v].ls,l,M,k)+qry(t[u].rs,t[v].rs,M+1,r,k);
}


//This program is written by Brian Peng.
#pragma GCC optimize("Ofast","inline","no-stack-protector")
#include<bits/stdc++.h>
using namespace std;
#define Rd(a) (a=read())
#define Gc(a) (a=getchar())
#define Pc(a) putchar(a)
int read(){
	register int x;register char c(getchar());register bool k;
	while(!isdigit(c)&&c^'-')if(Gc(c)==EOF)exit(0);
	if(c^'-')k=1,x=c&15;else k=x=0;
	while(isdigit(Gc(c)))x=(x<<1)+(x<<3)+(c&15);
	return k?x:-x;
}
void wr(register int a){
	if(a<0)Pc('-'),a=-a;
	if(a<=9)Pc(a|'0');
	else wr(a/10),Pc((a%10)|'0');
}
signed const INF(0x3f3f3f3f),NINF(0xc3c3c3c3);
long long const LINF(0x3f3f3f3f3f3f3f3fLL),LNINF(0xc3c3c3c3c3c3c3c3LL);
#define Ps Pc(' ')
#define Pe Pc('\n')
#define Frn0(i,a,b) for(register int i(a);i<(b);++i)
#define Frn1(i,a,b) for(register int i(a);i<=(b);++i)
#define Frn_(i,a,b) for(register int i(a);i>=(b);--i)
#define Mst(a,b) memset(a,b,sizeof(a))
#define File(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout)
#define N (2000010)
#define M ((l+r)>>1)
int n,h[N]{INF},rt[N],sz,s[N],tp,mx,mx2;
long long ans,cnt;
struct{int ls,rs,v;}t[N<<3];
int mdf(int u,int l,int r,int k);
int qry(int u,int v,int l,int r,int k);
signed main(){
	h[Rd(n)<<1|1]=INF;
	Frn1(i,1,n)(h[i+n]=Rd(h[i]))>mx?(mx=h[i],cnt=1):h[i]==mx?++cnt:0;
	Frn1(i,1,n<<1){
		while(h[i]>=h[s[tp]])--tp;
		rt[i]=mdf(rt[i-1],0,n<<1,s[tp]);
		s[++tp]=i;
	}
	s[tp=0]=n<<1|1;
	Frn_(i,n<<1,1){
		while(h[i]>=h[s[tp]])--tp;
		if(i<=n){
			if(s[tp]<i+n)++ans;
			ans+=qry(rt[i],rt[min(s[tp],i+n)-1],0,n<<1,i);
		}
		s[++tp]=i;
	}
	if(cnt==1){
		cnt=0;
		Frn1(i,1,n)if(h[i]<mx)h[i]>mx2?(mx2=h[i],cnt=1):h[i]==mx2?++cnt:0;
		ans-=cnt;
	}else ans-=(cnt*(cnt-1))>>1;
	wr(ans),exit(0);
}
int mdf(int u,int l,int r,int k){
	int re(++sz);t[re]=t[u];
	if(l==r){++t[re].v;return re;}
	k<=M?t[re].ls=mdf(t[u].ls,l,M,k):t[re].rs=mdf(t[u].rs,M+1,r,k);
	t[re].v=t[t[re].ls].v+t[t[re].rs].v;
	return re;
}
int qry(int u,int v,int l,int r,int k){
	if(r<=k)return t[v].v-t[u].v;
	if(l>k||t[u].v==t[v].v)return 0;
	return qry(t[u].ls,t[v].ls,l,M,k)+qry(t[u].rs,t[v].rs,M+1,r,k);
}