#include <bits/stdc++.h>
using namespace std;
priority_queue<pair<int, int>, vector<pair<int, int> >,
               greater<pair<int, int> > >
    pq;
int rm[500010];
int lm[500010];
int main() {
  int n;
  cin >> n;
  for (int i = 0; i < n; ++i) {
    int temp;
    cin >> temp;
    rm[i] = lm[i] = temp;
    pq.push(make_pair(temp, i));
  }
  long long answ = 0;
  int le = 0, re = n - 1;
  for (int t = n - 2; t > 0; --t) {
    int v = pq.top().second;
    pq.pop();
    if (v == le) {
      answ += rm[le];
      for (le = le + 1; rm[le] <= 0; le = -rm[le])
        ;
    } else if (v == re) {
      answ += lm[re];
      for (re = re - 1; lm[re] <= 0; re = -lm[re])
        ;
    } else {
      int l, r;
      stack<int> st = stack<int>();
      for (l = v - 1; lm[l] <= 0; l = -lm[l]) st.push(l);
      while (!st.empty()) {
        lm[st.top()] = -l;
        st.pop();
      }
      for (r = v + 1; rm[r] <= 0; r = -rm[r]) st.push(r);
      while (!st.empty()) {
        rm[st.top()] = -r;
        st.pop();
      }
      answ += min(lm[l], rm[r]);
      lm[v] = -l;
      rm[v] = -r;
    }
  }
  cout << answ << endl;
  return 0;
}
