#include <bits/stdc++.h>
using namespace std;
const int N = 1000005;
int num[N], l[N], r[N], c[N], temp[N];
int main() {
  int n, max1 = -1, p = -1;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &temp[i]);
    if (max1 < temp[i]) {
      max1 = temp[i];
      p = i;
    }
  }
  num[n] = temp[p];
  for (int i = 0; i < n; i++) {
    num[i] = temp[p++];
    p %= n;
  }
  for (int i = 1; i < n; i++) {
    l[i] = i - 1;
    while (l[i] > 0 && num[i] >= num[l[i]]) {
      l[i] = l[l[i]];
    }
  }
  c[n] = 0;
  for (int i = n - 1; i >= 0; i--) {
    r[i] = i + 1;
    while (r[i] < n && num[i] > num[r[i]]) r[i] = r[r[i]];
    if (r[i] < n && num[i] == num[r[i]]) {
      c[i] = c[r[i]] + 1;
      r[i] = r[r[i]];
    }
  }
  long long ans = 0;
  for (int i = 1; i < n; i++) {
    ans += c[i];
    ans += 2;
    if (l[i] == 0 && r[i] == n) ans--;
  }
  cout << ans << endl;
  return 0;
}
