#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-8;
const double pi = acos(-1.0);
const int N = 500005;
int s[N];
int main() {
  int n, top = 0;
  long long ans = 0;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    int x;
    scanf("%d", &x);
    while (top > 1 && s[top - 2] >= s[top - 1] && x >= s[top - 1]) {
      ans += min(x, s[top - 2]);
      top--;
    }
    s[top++] = x;
  }
  sort(s, s + top);
  for (int i = 0; i < top - 2; i++) ans += s[i];
  cout << ans << endl;
  return 0;
}
