#include <bits/stdc++.h>   const int SIZE = 5e5 + 5;   using namespace std;   vector<pair<int, int> > v;   set<pair<int, int> > H;   bool used[SIZE];   int b[SIZE];   int main() {     int(n);     scanf( %d , &n);     for (int i = 0; i < (n); ++i) {       int(x);       scanf( %d , &x);       v.push_back(make_pair(x, i));       H.insert(make_pair(i, x));     }     long long an = 0;     sort((v).begin(), (v).end());     for (int i = 0; i < (((int)(v).size())); ++i) {       if (v[i].second == 0 || v[i].second == n - 1) continue;       set<pair<int, int> >::iterator it =           H.lower_bound(make_pair(v[i].second, 0));       set<pair<int, int> >::iterator it2 = it;       int now = it->second;       it2--;       int tmp = it2->second;       it2++;       it2++;       tmp = min(it2->second, tmp);       if (now <= tmp) {         used[i] = 1;         an += tmp;         H.erase(it);       }     }     int bn = 0;     for (set<pair<int, int> >::iterator it = H.begin(); it != H.end(); it++) {       b[bn++] = it->second;     }     if (bn > 2) {       sort(b, b + bn);       for (int i = 0; i + 2 < bn; i++) an += b[i];     }     cout << an << endl;     return 0;   }   