#include <bits/stdc++.h>
using std::min;
const int N = 5e5 + 10;
int n;
long long tot, val[N], pre[N], nxt[N];
inline int calc(int p) {
  if (p == 1 or p == n) return 0;
  return min(val[pre[p]], val[nxt[p]]);
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i)
    scanf("%I64d", &val[i]), pre[i] = i - 1, nxt[i] = i + 1;
  for (int i = 2; i <= n - 1; i = nxt[i]) {
    while (val[pre[i]] >= val[i] and val[nxt[i]] >= val[i]) {
      tot += calc(i);
      nxt[pre[i]] = nxt[i];
      pre[nxt[i]] = pre[i];
      i = pre[i];
    }
  }
  int p = 0, maxval = 0;
  for (int i = nxt[1]; i <= n; i = nxt[i])
    if (calc(i) > maxval) p = i, maxval = calc(i);
  while (p > 1 and p < n) {
    tot += calc(p);
    nxt[pre[p]] = nxt[p];
    pre[nxt[p]] = pre[p];
    p = (calc(pre[p]) >= calc(nxt[p])) ? pre[p] : nxt[p];
  }
  printf("%I64d\n", tot);
  return 0;
}
