Artem and Array

Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn’t have an adjacent number to the left or right, Artem doesn’t get any points.

After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.

Input

The first line contains a single integer n (1 ≤ n ≤ 5·105) — the number of elements in the array. The next line contains n integers a i (1 ≤ a i ≤ 106) — the values of the array elements.

Output

In a single line print a single integer — the maximum number of points Artem can get.

Examples

input

5
3 1 5 2 6

output

11

input

5
1 2 3 4 5

output

6

input

5
1 100 101 100 1

output

102

Solution:

#include <cstring>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cassert>

using namespace std;

const int N = 1000010;

int a[N];
pair <int, int> p[N];
int pr[N], ne[N];

int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
    scanf("%d", a + i);
    p[i] = make_pair(a[i], i);
  }
  sort(p, p + n);
  for (int i = 0; i < n; i++) {
    pr[i] = i - 1;
    ne[i] = i + 1;
  }
  int low = 0, high = n - 1;
  long long ans = 0;
  for (int i = 0; i < n - 2; i++) {
    int j = p[i].second;
    if (j == low) {
      ans += p[i].first;
      low = ne[low];
      continue;
    }
    if (j == high) {
      ans += p[i].first;
      high = pr[high];
      continue;
    }
    int x = a[pr[j]];
    int y = a[ne[j]];
    if (x < y) {
      ans += x;
    } else {
      ans += y;
    }
    pr[ne[j]] = pr[j];
    ne[pr[j]] = ne[j];
  }
  cout << ans << endl;
  return 0;
}