#include <bits/stdc++.h>
using namespace std;
const int MAXN = 5e5 + 10;
int n, a[MAXN];
long long ans = 0;
int s[MAXN], cnt = 0;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
  }
  int top = 1;
  for (int i = 1; i <= n; i++) {
    int x = a[i];
    while (top > 2 && s[top - 2] >= s[top - 1] && s[top - 1] <= x) {
      ans += min(s[top - 2], x);
      top -= 1;
    }
    s[top++] = x;
  }
  top -= 1;
  sort(1 + s, 1 + s + top);
  for (int i = 1; i <= top - 2; i++) {
    ans += s[i];
  }
  cout << ans;
  return 0;
}
