#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
int n;
pair<long long int, int> a[N];
long long int backup[N];
long long int ans, base;
set<int> s;
int nxt(long long int x) {
  set<int>::iterator it;
  it = s.upper_bound(x);
  return *it;
}
int prv(long long int x) {
  set<int>::iterator it;
  it = s.lower_bound(x);
  it--;
  return *it;
}
int main() {
  cin >> n;
  for (int i = 0; i < n; ++i) {
    scanf("%lld", &(a[i].first));
    backup[i] = a[i].first;
    a[i].second = i;
    s.insert(i);
  }
  s.insert(-1);
  s.insert(n);
  sort(a, a + n);
  base = 0;
  int now;
  for (int i = 0; i < n - 2; ++i) {
    now = a[i].second;
    if ((prv(now) != -1) and (nxt(now) != n)) {
      ans += (min(backup[nxt(now)], backup[prv(now)]) - base);
    } else {
      ans += ((backup[now] - base) * (long long int)(n - 2 - i));
      base = backup[now];
    }
    s.erase(now);
  }
  cout << ans;
}
