#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e5 + 10;
int n, a[maxn], q[maxn];
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  long long ans = 0;
  q[1] = a[1];
  int p = 1;
  for (int i = 2; i <= n; i++) {
    while (q[p] <= a[i] && q[p] <= q[p - 1] && p > 1) {
      ans = ans + min(q[p - 1], a[i]);
      p--;
    }
    q[++p] = a[i];
  }
  sort(q, q + p + 1);
  for (int i = 1; i < p - 1; i++) ans = ans + q[i];
  cout << ans << endl;
  return 0;
}
