n = gets.to_i
p_array=gets.chomp.split(" ").map(&:to_i)

# memo[l][r]
memo = Hash.new{|hash, key| hash[key] = {}}

ret = 0
(0...(n-1)).each do |l|
    ((l+1)...n).each do |r|
        if l == r - 1
            pair = [p_array[l], p_array[r]].sort{|a, b| b <=> a }
            memo[l][r] = pair
            ret += pair[1]
        else 
            pair_p = [memo[l][r-1][0], memo[l][r-1][1], p_array[r]].sort {|a, b| b <=> a }
            pair = [pair_p[0], pair_p[1]]
            memo[l][r] = pair
            ret += pair[1]
        end    
    end
end

puts ret