#include <bits/stdc++.h>
using namespace std;
static char stdinBuffer[1024];
static char* stdinDataEnd = stdinBuffer + sizeof(stdinBuffer);
static const char* stdinPos = stdinDataEnd;
void readAheadHelper() {
  if (stdinDataEnd == stdinBuffer + sizeof(stdinBuffer)) {
    size_t remaining = stdinDataEnd - stdinPos;
    memmove(stdinBuffer, stdinPos, remaining);
    size_t sz = fread(stdinBuffer + remaining, 1,
                      sizeof(stdinBuffer) - remaining, stdin);
    stdinPos = stdinBuffer;
    stdinDataEnd = stdinBuffer + remaining + sz;
    if (stdinDataEnd != stdinBuffer + sizeof(stdinBuffer)) *stdinDataEnd = 0;
  }
}
void readAhead(size_t amount) {
  if (stdinDataEnd - stdinPos < amount) readAheadHelper();
}
unsigned readUint() {
  readAhead(16);
  unsigned x = 0;
  while (*stdinPos >= '0' && *stdinPos <= '9') {
    x *= 10;
    x += *stdinPos - '0';
    ++stdinPos;
  }
  ++stdinPos;
  return x;
}
int a[1000000];
pair<int, int> s[1000000];
int main(int argc, char** argv) {
  int n = readUint();
  int mx = 0, mxpos = 0;
  for (int i = 0; i < n; ++i) {
    a[i] = readUint();
    if (a[i] > mx) {
      mx = a[i];
      mxpos = i;
    }
  }
  long long count = 0;
  int ns = 0;
  s[ns++] = {a[mxpos], 1};
  for (int i = 1, j = mxpos; (++j == n ? j = 0 : 0), i < n; ++i) {
    while (a[j] > s[ns - 1].first) count += s[--ns].second;
    if (s[ns - 1].first == a[j])
      count += s[ns - 1].second++ + !!(ns > 1);
    else {
      ++count;
      s[ns++] = {a[j], 1};
    }
  }
  while (ns-- > 1)
    if (s[0].second > 1 || ns > 1) count += s[ns].second;
  cout << count << endl;
  return 0;
}
