#include <bits/stdc++.h>
namespace IO {
char buf[90];
}
template <typename T>
inline void qr(T &x) {
  char ch = getchar(), lst = ' ';
  while (ch > '9' || ch < '0') lst = ch, ch = getchar();
  while (ch >= '0' && ch <= '9')
    x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
  if (lst == '-') x = -x;
}
template <typename T>
inline void qw(T x, const char aft, const bool pt) {
  if (x < 0) x = -x, putchar('-');
  int top = 0;
  do {
    IO::buf[++top] = x % 10 + '0';
    x /= 10;
  } while (x);
  while (top) putchar(IO::buf[top--]);
  if (pt) putchar(aft);
}
template <typename T>
inline T mmax(const T a, const T b) {
  return a > b ? a : b;
}
template <typename T>
inline T mmin(const T a, const T b) {
  return a < b ? a : b;
}
template <typename T>
inline T mabs(const T a) {
  return a < 0 ? -a : a;
}
template <typename T>
inline void mswap(T &a, T &b) {
  T temp = a;
  a = b;
  b = temp;
}
const int maxn = 1000010;
struct M {
  int a, b;
};
M stack[maxn];
int n, top;
int MU[maxn], CU[maxn];
bool used[maxn];
int main() {
  qr(n);
  for (register int i = 1; i <= n; ++i) qr(MU[i]);
  register int mx = 0;
  for (register int i = 1; i <= n; ++i)
    if (MU[i] > MU[mx]) mx = i;
  for (register int i = mx; i <= n; ++i) CU[++top] = MU[i];
  for (register int i = 1; i < mx; ++i) CU[++top] = MU[i];
  mx = 0;
  register long long int ans = 0;
  stack[top = 1] = (M){CU[1], 1};
  for (register int i = 2; i <= n; ++i) {
    while (top && (stack[top].a < CU[i])) ans += stack[top--].b;
    if (stack[top].a == CU[i])
      ans += (stack[top].b++) + (top > 1);
    else {
      stack[++top] = (M){CU[i], 1};
      ++ans;
    }
  }
  mx = 0;
  for (register int i = 2; i <= n; ++i)
    if (CU[i] >= mx) {
      mx = CU[i];
      used[i] = true;
    }
  mx = 0;
  for (register int i = n; i > 1; --i)
    if (CU[i] >= mx) {
      if (!used[i]) ++ans;
      mx = CU[i];
    }
  qw(ans, '\n', true);
  return 0;
}
