#include <bits/stdc++.h>
#pragma GCC optimize("-Ofast", "-funroll-all-loops")
using namespace std;
const long long N = 5e5 + 10;
long long a[N], n, res, top, s[N];
signed main() {
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    scanf("%lld", &a[i]);
    while (top >= 2) {
      if (s[top] <= s[top - 1] && a[i] >= s[top])
        res += min(s[--top], a[i]);
      else
        break;
    }
    s[++top] = a[i];
  }
  sort(s + 1, s + 1 + top);
  for (long long i = 1; i < top - 1; i++) res += s[i];
  cout << res;
  return 0;
}
