#include <bits/stdc++.h>
using namespace std;
const int N = 1000000 + 10;
int d[N];
int v[N];
pair<int, int> st[N];
int top;
int main() {
  int n;
  while (scanf("%d", &n) == 1) {
    top = 0;
    int maxa = -1, mi = -1;
    for (int i = 0; i < n; ++i) {
      v[i] = 0;
      scanf("%d", &d[i]);
      if (d[i] > maxa) {
        maxa = d[i];
        mi = i;
      }
    }
    if (d[mi] == d[(mi + 1) % n]) {
      mi = (mi + 1) % n;
    }
    long long ans = 0;
    for (int i = 0; i < n; ++i) {
      int key = d[(i + mi) % n];
      while (top && st[top - 1].first < key) {
        top--;
        ans += st[top].second;
      }
      if (top) {
        if (st[top - 1].first == key) {
          ans += st[top - 1].second;
          st[top - 1].second++;
          if (top - 1 > 0) {
            ans++;
          }
          if (st[0].second == 1 && (top == 1 || top == 2)) {
            v[(i + mi) % n] = 1;
          }
        } else {
          ans += 1;
          if (st[0].second == 1 && top == 1) {
            v[(i + mi) % n] = 1;
          }
          st[top++] = pair<int, int>(key, 1);
        }
      } else {
        st[top++] = pair<int, int>(key, 1);
      }
    }
    top = 1;
    if (1) {
      for (int i = 1; i < n; ++i) {
        int key = d[(mi - i % n + n) % n];
        if (key == maxa) break;
        while (top && key >= st[top - 1].first) {
          --top;
        }
        if (top == 1 && v[(mi - i % n + n) % n] != 1) {
          ans++;
        }
        st[top++] = pair<int, int>(key, 1);
      }
    }
    cout << ans << endl;
  }
}
