#include <bits/stdc++.h>
using namespace std;
const int maxN = 500005;
int n, s[maxN], sta[maxN];
void Readln() {
  scanf("%d\n", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &s[i]);
}
void Solve() {
  if (n <= 2) {
    printf("0\n");
    return;
  }
  int tot = 2;
  sta[1] = s[1];
  sta[2] = s[2];
  long long ans = 0;
  for (int i = 3; i <= n; i++) {
    while (tot > 1 && sta[tot] <= sta[tot - 1] && sta[tot] <= s[i]) {
      ans += min(sta[tot - 1], s[i]);
      tot--;
    }
    tot++;
    sta[tot] = s[i];
  }
  sort(sta + 1, sta + 1 + tot);
  for (int i = 1; i <= tot - 2; i++) ans += sta[i];
  printf("%I64d\n", ans);
}
int main() {
  Readln();
  Solve();
  return 0;
}
