#include <bits/stdc++.h>
using namespace std;
long long n, a[2000010], l[2000010], r[2000010], maxi, pos, b[2000010],
    s[2000010], r2[2000010], ans;
signed main() {
  ios::sync_with_stdio(false);
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    cin >> a[i];
    if (maxi < a[i]) {
      maxi = a[i];
      pos = i;
    }
  }
  for (long long i = pos; i <= n; i++) b[i - pos] = a[i];
  for (long long i = 1; i <= pos; i++) b[n - pos + i] = a[i];
  stack<long long> st1, st2, st3;
  for (long long i = 0; i <= n; i++) {
    r[i] = r2[i] = n;
    while (!st1.empty() && b[st1.top()] < b[i]) {
      r[st1.top()] = i;
      st1.pop();
    }
    st1.push(i);
    while (!st3.empty() && b[st3.top()] <= b[i]) {
      r2[st3.top()] = i;
      st3.pop();
    }
    st3.push(i);
  }
  for (long long i = n; i >= 0; i--) {
    l[i] = 0;
    while (!st2.empty() && b[st2.top()] < b[i]) {
      l[st2.top()] = i;
      st2.pop();
    }
    st2.push(i);
  }
  for (long long i = n - 1; i >= 0; i--)
    if (r2[i] < n && b[i] == b[r2[i]]) s[i] = s[r2[i]] + 1;
  for (long long i = 0; i < n; i++) {
    ans += s[i];
    if (b[i] == b[0]) continue;
    if (l[i] == 0 && r[i] == n)
      ans++;
    else
      ans += 2;
  }
  cout << ans;
  return 0;
}
