n = gets.chomp.to_i

plist = gets.chomp.split.collect{ |item| item.to_i}

ans = 0

0.upto(n-2) do |l|
  nowmax = plist[l]
  nowsec = 0
  (l+1).upto(n-1) do |r|
    if plist[r] >= nowmax
      nowsec = nowmax
      nowmax = plist[r]
    elsif plist[r] > nowsec
      nowsec = plist[r]
    end
    ans += nowsec
  end
end

puts ans
