#include <bits/stdc++.h>
using namespace std;
int n, a[500010], b[500010], p = 0;
long long ans;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    while (p >= 2 && b[p - 2] >= b[p - 1] && a[i] >= b[p - 1])
      ans += min(b[p - 2], a[i]), p--;
    b[p] = a[i];
    p++;
  }
  sort(b, b + p);
  for (int i = 0; i <= p - 3; i++) ans += b[i];
  printf("%lld", ans);
  return 0;
}
