#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1);
const double eps = 1e-9;
const int inf = 2000000000;
const long long infLL = 9000000000000000000;
inline int in() {
  int x;
  scanf("%d", &x);
  return x;
}
inline long long inl() {
  long long x;
  scanf("%I64d", &x);
  return x;
}
inline double ind() {
  double x;
  scanf("%lf", &x);
  return x;
}
inline bool EQ(double a, double b) { return fabs(a - b) < 1e-9; }
inline bool isLeapYear(long long year) {
  return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
}
inline void normal(long long &a) {
  a %= 1000000007;
  (a < 0) && (a += 1000000007);
}
inline long long modMul(long long a, long long b) {
  a %= 1000000007, b %= 1000000007;
  normal(a), normal(b);
  return (a * b) % 1000000007;
}
inline long long modAdd(long long a, long long b) {
  a %= 1000000007, b %= 1000000007;
  normal(a), normal(b);
  return (a + b) % 1000000007;
}
inline long long modSub(long long a, long long b) {
  a %= 1000000007, b %= 1000000007;
  normal(a), normal(b);
  a -= b;
  normal(a);
  return a;
}
inline long long modPow(long long b, long long p) {
  long long r = 1;
  while (p) {
    if (p & 1) r = modMul(r, b);
    b = modMul(b, b);
    p >>= 1;
  }
  return r;
}
inline long long modInverse(long long a) { return modPow(a, 1000000007 - 2); }
inline long long modDiv(long long a, long long b) {
  return modMul(a, modInverse(b));
}
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
int power(int x, int n) {
  if (n == 0)
    return 1;
  else if (n % 2 == 0) {
    int y = power(x, n / 2);
    return y * y;
  } else
    return x * power(x, n - 1);
}
const int si = 1e6 + 10;
int a[si], le[si], ri[si], sa[si];
stack<int> st;
int main() {
  int n = in();
  for (int i = 0; i < n; i++) {
    a[i] = in();
  }
  rotate(a, max_element(a, a + n), a + n);
  a[n] = a[0];
  le[0] = -1;
  st.push(0);
  for (int i = 1; i < n; i++) {
    while (!st.empty() && a[st.top()] <= a[i]) {
      if (a[st.top()] == a[i]) {
        sa[i] = sa[st.top()] + 1;
      }
      st.pop();
    }
    if (st.empty()) {
      le[i] = -1;
    } else {
      le[i] = st.top();
    }
    st.push(i);
  }
  while (!st.empty()) {
    st.pop();
  }
  ri[n] = n;
  st.push(n);
  for (int i = n - 1; i > 0; i--) {
    while (!st.empty() && a[st.top()] <= a[i]) {
      st.pop();
    }
    if (st.empty()) {
      ri[i] = n + 1;
    } else {
      ri[i] = st.top();
    }
    st.push(i);
  }
  long long ans = 0;
  for (int i = 1; i < n; i++) {
    if (le[i] != -1) {
      ans++;
    }
    if (ri[i] != n + 1) {
      ans++;
    }
    if (le[i] == 0 && ri[i] == n) ans--;
    ans += sa[i];
  }
  printf("%I64d\n", ans);
  return 0;
}
