#include <bits/stdc++.h>
using namespace std;
inline long long in() {
  int32_t x;
  scanf("%d", &x);
  return x;
}
inline long long lin() {
  long long x;
  scanf("%lld", &x);
  return x;
}
const long long maxn = 5e5 + 10;
const long long inf = 1e18;
long long STACK[maxn], t, a[maxn];
int32_t main() {
  long long n = in();
  for (long long i = 0; i < n; i++) a[i] = in();
  long long ans = 0;
  for (long long i = 0; i < n; i++) {
    while (t >= 2 && STACK[t - 2] >= STACK[t - 1] && a[i] >= STACK[t - 1])
      ans += min(STACK[t - 2], a[i]), t--;
    STACK[t++] = a[i];
  }
  sort(STACK, STACK + t);
  for (long long i = 0; i < t - 2; i++) ans += STACK[i];
  cout << ans << endl;
}
