#include <bits/stdc++.h>
const int MAXN = 500017;
const int MAXLOG = 42;
const long long INF = 1000000000000000000;
using namespace std;
set<int> ind;
set<pair<int, int>> s;
int a[MAXN];
int b[MAXN];
void mainp() {
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) cin >> a[i];
  long long sum = 0ll;
  int p = 0;
  for (int i = 0; i < n; i++) {
    while (p >= 2 && b[p - 2] >= b[p - 1] && a[i] >= b[p - 1])
      sum += min(a[i], b[p - 2]), p--;
    b[p] = a[i];
    p++;
  }
  sort(b, b + p);
  for (int i = 0; i < p - 2; i++) sum += b[i];
  cout << sum << endl;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  mainp();
  return 0;
}
