#include <bits/stdc++.h>
using namespace std;
const long long INF64 = ((long long)1E18);
const int INF = 1E9 + 7;
template <class C>
void mini(C& a4, C b4) {
  a4 = min(a4, b4);
}
template <class C>
void maxi(C& a4, C b4) {
  a4 = max(a4, b4);
}
template <typename T1, typename T2>
ostream& operator<<(ostream& out, pair<T1, T2> pair) {
  out << "(" << pair.first << ", " << pair.second << ")";
  return out;
}
map<int, int> mapa;
void dodaj(pair<int, int> t) { mapa[t.second] = t.first; }
int main() {
  ios_base::sync_with_stdio(false);
  vector<pair<int, int> > t;
  int n;
  cin >> n;
  for (int i = (1); i <= (n); ++i) {
    int a;
    cin >> a;
    t.push_back(make_pair(a, i));
  }
  sort((t).begin(), (t).end());
  reverse((t).begin(), (t).end());
  if (n <= 2) {
    cout << 0 << endl;
    return 0;
  }
  for (int i = (0); i <= (1); ++i) dodaj(t[i]);
  long long sum = 0;
  for (int i = (2); i <= (n - 1); ++i) {
    int x = t[i].second;
    int y = t[i].first;
    if (x < mapa.begin()->first) {
      sum += y;
      dodaj(t[i]);
      continue;
    }
    auto it = mapa.end();
    it--;
    if (x > it->first) {
      sum += y;
      dodaj(t[i]);
      continue;
    }
    auto wie = mapa.upper_bound(x);
    auto mie = wie;
    mie--;
    sum += min(wie->second, mie->second);
    dodaj(t[i]);
  }
  cout << sum << endl;
  return 0;
}
