#include <bits/stdc++.h>
using namespace std;
long long const N = 5e5 + 20;
long long n, a[N], x, ans, l[N], r[N];
set<pair<long long, long long> > s;
int32_t main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (long long i = 1; i <= n; i++) cin >> a[i];
  for (long long i = 0; i <= n + 1; i++) l[i] = i - 1, r[i] = i + 1;
  for (long long i = 1; i <= n; i++) s.insert({a[i], i});
  while (s.size() > 2) {
    long long k = (*s.begin()).first - x, i = (*s.begin()).second;
    s.erase(s.begin());
    if (l[i] == 0) {
      x += k;
      ans += k * (s.size() - 1);
    } else if (r[i] == n + 1) {
      x += k;
      ans += k * (s.size() - 1);
    } else
      ans += min(a[l[i]] - x, a[r[i]] - x);
    l[r[i]] = l[i], r[l[i]] = r[i];
  }
  return cout << ans, 0;
}
