#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3fffffff;
const int MOD = 1000000007;
int n, top;
int a, s[5 * 100010];
int main() {
  scanf("%d", &n);
  unsigned long long ans = 0;
  for (int i = 0; i < n; i++) {
    scanf("%d", &a);
    while (top - 2 >= 0 && s[top - 2] >= s[top - 1] && a >= s[top - 1]) {
      ans += min(s[top - 2], a);
      top--;
    }
    s[top++] = a;
  }
  sort(s, s + top);
  for (int i = 0; i < top - 2; i++) ans += s[i];
  printf("%lld\n", ans);
  return 0;
}
