#include <bits/stdc++.h>
using namespace std;
pair<int, int> a[500009];
int tree[500009], n = 500004, b[500009];
void update(int idx, int val) {
  while (idx <= n) {
    tree[idx] += val;
    idx += (idx & -idx);
  }
}
int sum(int idx) {
  int val = 0;
  while (idx > 0) {
    val += tree[idx];
    idx -= (idx & -idx);
  }
  return val;
}
int query(int val) {
  int low = 0;
  int high = n;
  int mid = (low + high) / 2;
  while (low < high) {
    int mid = (low + high) / 2;
    if (sum(mid) >= val)
      high = mid;
    else
      low = mid + 1;
  }
  return low;
}
int main() {
  int N;
  scanf("%d", &N);
  if (N <= 2) {
    printf("0\n");
    return 0;
  }
  for (int i = int(1); i <= int(N); i++) {
    scanf("%d", &a[i].first);
    a[i].second = i;
    b[i] = a[i].first;
  }
  sort(a + 1, a + N + 1);
  reverse(a + 1, a + N + 1);
  update(a[1].second, 1);
  update(a[1].second, 1);
  update(a[2].second, 1);
  update(a[2].second, 1);
  long long int ans = 0;
  for (int i = int(3); i <= int(N); i++) {
    int idx = a[i].second;
    update(a[i].second, 1);
    if (query(sum(idx) - 1) != 0 && query(sum(idx) + 1) != n) {
      ans += min(b[query(sum(idx) - 1)], b[query(sum(idx) + 1)]);
    } else if (query(sum(idx) + 2) != n) {
      ans += min(a[i].first, b[query(sum(idx) + 2)]);
    } else if (query(sum(idx) - 2) != 0) {
      ans += min(a[i].first, b[query(sum(idx) - 2)]);
    }
  }
  printf("%lld\n", ans);
  return 0;
}
