#include <bits/stdc++.h>
using namespace std;
int n, a[2000005], ps = 0;
pair<int, int> s[1000005];
int main() {
  scanf("%d", &n);
  int mx = 1;
  for (int i = 1; i <= n; i++) {
    scanf("%d", a + i);
    if (a[i] > a[mx]) mx = i;
  }
  for (int i = 1; i <= mx; i++) a[n + i] = a[i];
  s[ps] = make_pair(a[mx], 1);
  long long ans = 0;
  for (int i = mx + 1; i < mx + n; i++) {
    while (a[i] > s[ps].first) {
      ans +=
          (long long)s[ps].second * (s[ps].second - 1) / 2 + s[ps].second * 2;
      ps--;
    }
    if (a[i] == s[ps].first)
      s[ps].second++;
    else {
      s[++ps] = make_pair(a[i], 1);
    }
  }
  for (; ps; ps--) {
    ans += (long long)s[ps].second * (s[ps].second - 1) / 2 +
           s[ps].second * (2 - (ps == 1 && s[0].second == 1));
  }
  ans += (long long)s[0].second * (s[0].second - 1) / 2;
  cout << ans << endl;
  return 0;
}
