#include<bits/stdc++.h>
#define el '\n'
using namespace std;
typedef long long ll;
void fastip()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
}
int main(){
    fastip();
    int n;
    cin >> n;
    vector<int> a(n+1);
    vector<ll> cpair(n+1, 0), re(n+1, 0);
    stack<int> s;
    ll cnt=0;
    for (ll i=1; i<=n; i++){
        cin >> a[i];
        while (!s.empty() && a[i]>=a[s.top()]){
            if(a[i]==a[s.top()]) re[i]= re[s.top()] +1;
            cpair[i]+= re[s.top()] +1;
            s.pop();
        }
        if (!s.empty() && a[i]<a[s.top()]) cpair[i]++;
        cnt+=cpair[i];
        s.push(a[i]);
    }
    cout << cnt;
    return 0;
}
