module app;

import std.algorithm;
import std.array;
import std.bigint;
import std.conv;
import std.stdio;
import std.string;

void main()
{
	auto input = parseInput();
    auto result = main2(input);	
	writefln("%d", result);
}

int main2(Input input)
{
    int count = 0;
    auto n = input.n;
    for (int l = 1; l <= n-1; l++)
    {
        int lastMax1 = 0;
        int lastMax2 = 0;
        for (int r = l + 1; r <= n; r++)
        {
            int max1 = 0;
            int max2 = 0;
            if (lastMax1 != 0)
            {
                max1 = lastMax1;
                max2 = lastMax2;
                int p = input.p[r-1];
                if (p > max1)
                {
                    max2 = max1;
                    max1 = p;
                }
                else if (p > max2)
                {
                    max2 = p;
                }
            }
            else
            {
                max1 = max(input.p[l-1], input.p[r-1]);
                max2 = min(input.p[l-1], input.p[r-1]);
            }
            count += max2;
            lastMax1 = max1;
            lastMax2 = max2;
        }
    }
    return count;
}


unittest
{
    Input input = {3,[2,3,1]};
    auto result = main2(input);
    assert(result == 5);
}
unittest
{
    Input input = {5,[1,2,3,4,5]};
    auto result = main2(input);
    assert(result == 30);
}
unittest
{
    Input input = {8,[8,2,7,3,4,5,6,1]};
    auto result = main2(input);
    assert(result == 136);
}


struct Input
{
	int n;
    int[] p;
}

Input parseInput()
{
	Input input;
	input.n = readln().strip().to!int;
    input.p = readln().strip().split().map!(a => a.to!int).array;
	return input;
}
