unittest
{
	assert( [ "3", "2 3 1" ].parse.expand.solve == 5 );
	assert( [ "5", "1 2 3 4 5" ].parse.expand.solve == 30 );
	assert( [ "8", "8 2 7 3 4 5 6 1" ].parse.expand.solve == 136 );
}



import std.conv;
import std.range;
import std.stdio;
import std.typecons;

void main()
{
	stdin.byLineCopy.parse.expand.solve.writeln;
}

auto parse( Range )( Range input )
if( isInputRange!Range && is( ElementType!Range == string ) )
{
	input.popFront;
	auto ps = input.front.split.to!( long[] );
	return tuple( ps );
}

auto solve( long[] ps )
{
	auto ans = 0L;
	
	for( auto l = 0L; l < ps.length; l++ )
	{
		auto f = ps[ l ];
		auto s = 0L;
		for( auto r = l + 1; r < ps.length; r++ )
		{
			if( f < ps[ r ] )
			{
				s = f;
				f = ps[ r ];
			}
			else if( s < ps[ r ] )
			{
				s = ps[ r ];
			}
			ans += s;
		}
	}
	return ans;
}
