#include <bits/stdc++.h>
using namespace std;
int n, a[500001];
int main() {
  scanf("%d", &n);
  int i, top = -1;
  long long ans = 0;
  for (i = 1; i <= n; i++) {
    int x;
    scanf("%d", &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);
  return 0;
}
