#include <bits/stdc++.h>   using namespace std;   long long LLMAX = 9223372036854775807LL;   const int MOD = 1000000007;   const int maxn = 500001;   int n;   int a[maxn];   pair<int, int> p[maxn];   int pr[maxn], ne[maxn];   int main() {     scanf( %d , &(n));     for (int(i) = 0; (i) < (int)(n); ++(i)) scanf( %d , &(a[i]));     for (int i = 0; i < n; ++i) {       p[i] = make_pair((a[i]), (i));       pr[i] = i - 1;       ne[i] = i + 1;     }     sort(p, p + n);     long long ans = 0, l = 0, r = n - 1;     for (int i = 0; i < n - 2; ++i) {       int j = p[i].second;       if (j == l) {         ans += p[i].first;         l = ne[j];       } else if (j == r) {         ans += p[i].first;         r = pr[r];       } else {         ans += min(a[pr[j]], a[ne[j]]);         pr[ne[j]] = pr[j];         ne[pr[j]] = ne[j];       }     }     cout << ans << endl;   }   