#include <bits/stdc++.h>
inline int Get() {
  char ch;
  while ((ch = getchar()) < '0' || ch > '9')
    ;
  int Num = ch - '0';
  while ((ch = getchar()) >= '0' && ch <= '9')
    Num = (Num << 3) + (Num << 1) + ch - '0';
  return Num;
}
const int N = 5e5 + 5;
int n, a[N], id[N], l[N], r[N];
inline bool cmp(const int &x, const int &y) { return a[x] < a[y]; }
int main() {
  n = Get();
  for (int i = 1; i <= n; ++i) a[i] = Get(), id[i] = i;
  for (int i = 1; i < n; ++i) r[l[i + 1] = i] = i + 1;
  std ::sort(id + 1, id + n + 1, cmp);
  long long ans = 0;
  for (int i = 1, Min = 0, k; k = id[i], i <= n; ++i) {
    if (a[id[i]] != a[id[i - 1]]) {
      if (n - i + 1 > 2) ans += (long long)(n - i - 1) * (a[k] - Min);
      Min = a[k];
    }
    if (l[k] && r[k]) ans += std ::min(a[l[k]], a[r[k]]) - Min;
    r[l[k]] = r[k], l[r[k]] = l[k];
  }
  printf("%I64d\n", ans);
}
