#include <bits/stdc++.h>
using namespace std;
long long n, a[500005];
int main() {
  int i;
  long long ans = 0, x, top = -1;
  scanf("%lld", &n);
  while (n--) {
    scanf("%lld", &x);
    while (top >= 1 && a[top] <= a[top - 1] && a[top] <= x) {
      ans += min(a[top - 1], x);
      top--;
    }
    a[++top] = x;
  }
  sort(a, a + (top + 1));
  for (i = 0; i < top - 1; i++) ans += a[i];
  printf("%lld\n", ans);
}
