#include <bits/stdc++.h>
using namespace std;
map<pair<int, int>, pair<int, int> > s;
int n;
int a[500100];
int main() {
  cin >> n;
  int i, j, k;
  long long ans = 0;
  for (i = 0; i < n; i++) {
    cin >> j;
    a[i] = j;
  }
  for (i = 0; i < n; i++) {
    pair<int, int> tmp1(a[i], i), tmp2(i - 1, i + 1);
    s[make_pair(a[i], i)] = make_pair(i - 1, i + 1);
  }
  long long sd = 0;
  for (i = 0; i < n - 2; i++) {
    map<pair<int, int>, pair<int, int> >::iterator mn = s.begin();
    pair<int, int> val = mn->first;
    pair<int, int> nb = mn->second;
    s.erase(mn);
    if (nb.first == -1 || nb.second == n) {
      ans += (n - i - 2) * (val.first - sd);
      sd += (val.first - sd);
    } else
      ans += min(a[nb.first], a[nb.second]) - sd;
    pair<int, int> nbkey = make_pair(a[nb.first], nb.first);
    int left, right;
    if (nb.first >= 0) {
      left = s[nbkey].first;
      right = nb.second;
      s[nbkey] = make_pair(left, right);
    }
    nbkey = make_pair(a[nb.second], nb.second);
    if (nb.second <= n - 1) {
      right = s[nbkey].second;
      left = nb.first;
      s[nbkey] = make_pair(left, right);
    }
  }
  cout << ans;
  return 0;
}
