#include <bits/stdc++.h>
using namespace std;
enum { N = 500002 };
enum { C = 1000001 };
set<pair<pair<int, int>, pair<int, int> > > s;
int n, a[N];
long long cnt = 0, sum = 0;
pair<pair<int, int>, pair<int, int> > elem, neigh;
void count() {
  while (s.size() > 2) {
    elem = *s.begin();
    s.erase(s.begin());
    if (elem.second.first == -1 || elem.second.second == n) {
      cnt += (s.size() - 1) * (elem.first.first - sum);
      sum = elem.first.first;
    } else
      cnt += min(a[elem.second.first], a[elem.second.second]) - sum;
    if (elem.second.first != -1) {
      neigh = make_pair(make_pair(a[elem.second.first], elem.second.first),
                        make_pair(-1, elem.first.second));
      neigh = *s.lower_bound(neigh);
      s.erase(neigh);
      neigh.second.second = elem.second.second;
      s.insert(neigh);
    }
    if (elem.second.second != n) {
      neigh = make_pair(make_pair(a[elem.second.second], elem.second.second),
                        make_pair(elem.first.second, 0));
      neigh = *s.lower_bound(neigh);
      s.erase(neigh);
      neigh.second.first = elem.second.first;
      s.insert(neigh);
    }
  }
}
int main() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    s.insert(make_pair(make_pair(a[i], i), make_pair(i - 1, i + 1)));
  }
  count();
  cout << cnt;
  return 0;
}
