#include <bits/stdc++.h>
using namespace std;
const int MN = 500111;
int a[MN], res[MN], cur, left_[MN], right_[MN], st[MN], n;
int it[MN * 3];
int better(int x, int y) {
  if (!x) return y;
  if (!y) return x;
  if (a[x] > a[y])
    return x;
  else
    return y;
}
void buildTree(int i, int l, int r) {
  if (l == r) {
    it[i] = l;
    return;
  }
  int mid = (l + r) >> 1;
  buildTree(((i) << 1), l, mid);
  buildTree((((i) << 1) + 1), mid + 1, r);
  it[i] = better(it[((i) << 1)], it[(((i) << 1) + 1)]);
}
int getMin(int i, int l, int r, int u, int v) {
  if (v < l || r < u) return 0;
  if (u <= l && r <= v) return it[i];
  int res = u;
  int mid = (l + r) >> 1;
  res = better(getMin(((i) << 1), l, mid, u, v), res);
  res = better(getMin((((i) << 1) + 1), mid + 1, r, u, v), res);
  return res;
}
void init() {
  int top = 0;
  st[0] = 0;
  for (int i = (1), _b = (n); i <= _b; i++) {
    while (top && a[st[top]] < a[i]) --top;
    left_[i] = st[top];
    st[++top] = i;
  }
  top = 0;
  st[0] = n + 1;
  for (int i = (n), _b = (1); i >= _b; i--) {
    while (top && a[st[top]] < a[i]) --top;
    right_[i] = st[top];
    st[++top] = i;
  }
}
void solve(int l, int r) {
  if (l + 1 >= r) return;
  if (a[l] <= a[r]) {
    int u = right_[l];
    if (u == r) {
      u = getMin(1, 1, n, l + 1, r - 1);
    }
    res[cur--] = u;
    solve(l, u);
    solve(u, r);
  } else {
    int u = left_[r];
    if (u == l) {
      u = getMin(1, 1, n, l + 1, r - 1);
    }
    res[cur--] = u;
    solve(l, u);
    solve(u, r);
  }
}
int main() {
  ios ::sync_with_stdio(false);
  while (cin >> n) {
    for (int i = (1), _b = (n); i <= _b; i++) cin >> a[i];
    init();
    buildTree(1, 1, n);
    cur = n - 2;
    solve(1, n);
    set<int> s;
    for (int i = (1), _b = (n); i <= _b; i++) s.insert(i);
    long long sum = 0;
    for (int turn = (1), _b = (n - 2); turn <= _b; turn++) {
      int u = res[turn];
      s.erase(u);
      __typeof(s.begin()) next = s.lower_bound(u), prev = next;
      --prev;
      sum += min(a[*next], a[*prev]);
    }
    cout << sum << endl;
  }
  return 0;
}
