n=gets.to_i
a=gets.chomp.split(" ").map(&:to_i)
b=[]
re=0
(n-1).times do |i|
  if a[i]<a[i+1]
    b<<a[i]
    b<<a[i+1]
  else
    b<<a[i+1]
    b<<a[i]
  end
  re+=b[0]
  (n-i-2).times do |k|
    if a[i+k+2] <= b[0]
      re+=b[0]
      next
    elsif a[i+k+2] > b[0] && a[i+k+2] <=b[1]
      b.shift
      b.unshift(a[i+k+2])
      re+=b[0]
    else
      b.shift
      b << a[i+k+2]
      re+=b[0]
    end
  end
  b=[]
end
  puts re
    