#include <bits/stdc++.h>
using namespace std;
int n;
int b[500000 + 5];
int main() {
  while (cin >> n) {
    long long ans = 0;
    int r = -1;
    for (int i = 0; i < n; i++) {
      int tmp;
      scanf("%d", &tmp);
      while (r > 0 && b[r] <= b[r - 1] && b[r] <= tmp) {
        ans += min(b[r - 1], tmp);
        r--;
      }
      b[++r] = tmp;
    }
    sort(b, b + r + 1);
    for (int i = 0; i <= r - 2; i++) ans += b[i];
    cout << ans << endl;
  }
}
