n = gets.to_i
p = gets.split(' ').map(&:to_i)

sum = 0
(0..n-2).to_a.each do |i|
  best = 0
  second = 0
  (i+1..n-1).to_a.each do |j|
    if j == i+1
      best = p[i..j].max
      second = p[i..j].min
    elsif best < p[j]
      second = best
      best = p[j]
    elsif second < p[j]
      second = p[j]
    end
    sum += second
  end
end

print "#{sum}"
