#include <bits/stdc++.h>
using namespace std;
inline int Get() {
  int res = 0, q = 1;
  char ch = getchar();
  while ((ch < '0' || ch > '9') && ch != '-') ch = getchar();
  if (ch == '-') q = -1, ch = getchar();
  while (ch >= '0' && ch <= '9') res = res * 10 + ch - '0', ch = getchar();
  return res * q;
}
const double eps = 1e-12, pi = M_PI;
const int oo = (int)2e9, mod = (int)1e9 + 7;
const long long INF = (long long)1e17;
const int N = (int)5e5;
typedef long long arr[N + 10];
long long ans;
int i, j, k, p, n;
struct stack {
  arr v;
  long long top;
} st;
int main() {
  scanf(
      "%d"
      "\n",
      &n);
  scanf("%I64d", &st.v[++st.top]);
  for (int i = (2), end = (n); i <= end; ++i) {
    scanf("%d", &p);
    for (; st.v[st.top - 1] >= st.v[st.top] && p >= st.v[st.top];
         ans += ((st.v[st.top - 1]) < (p) ? (st.v[st.top - 1]) : (p)), --st.top)
      ;
    st.v[++st.top] = p;
  }
  sort(st.v + 1, st.v + st.top + 1);
  for (int i = (1), end = (st.top - 2); i <= end; ++i) ans += st.v[i];
  printf(
      "%I64d"
      "\n",
      ans);
  return 0;
}
