#include <bits/stdc++.h>
using namespace std;
stack<int> st;
long long n, s1, s2, ans, a[1000005], b[1000005], l[1000005];
int main() {
  scanf("%lld", &n);
  for (int i = 0; i < n; i++) scanf("%lld", &b[i]);
  for (int i = 0; i < n; i++) s1 = max(s1, b[i]);
  for (int i = 0; i < n; i++)
    if (b[i] == s1) {
      s1 = i;
      break;
    }
  for (int i = 0; i < n; i++)
    if (i < s1)
      a[(i + n - s1) % n + 1] = b[i];
    else
      a[i - s1 + 1] = b[i];
  a[n + 1] = a[1];
  for (int i = 1; i <= n; i++) ans += (a[i] == a[1]);
  ans = ans * (ans - 1) / 2;
  for (int i = n; i >= 0; i--) {
    while ((!st.empty()) && (a[st.top()] < a[i])) {
      b[st.top()] = i;
      st.pop();
    }
    st.push(i);
  }
  while (!st.empty()) st.pop();
  for (int i = 1; i <= n + 1; i++) {
    s1 = -1;
    while ((!st.empty()) && (a[st.top()] < a[i])) {
      if (s1 != a[st.top()]) {
        s1 = a[st.top()];
        s2 = 0;
      }
      ans += (++s2) + ((b[st.top()] > 1) || (i < n + 1));
      st.pop();
    }
    st.push(i);
  }
  printf("%lld", ans);
}
