#include <bits/stdc++.h>
using namespace std;
int n;
int a[500050];
int st[500050];
int main() {
  int top = 0;
  long long sum = 0;
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) {
    scanf("%d", &a[i]);
    st[top++] = a[i];
    while (top > 2 && st[top - 2] <= st[top - 1] &&
           st[top - 2] <= st[top - 3]) {
      sum += std::min(st[top - 1], st[top - 3]);
      st[top - 2] = st[top - 1];
      top--;
    }
  }
  sort(st, st + top);
  for (int i = 0; i < top - 2; ++i) sum += st[i];
  printf("%I64d\n", sum);
}
