class SegmentTree
  MIN_VALUE = -1

  def initialize(size)
    n = 1
    while n < size
      n *= 2
    end
    @size = n
    @data = Array.new(n * 2 - 1, [MIN_VALUE, MIN_VALUE])
  end

  # 0-origin
  def update(k, a)
    k += @size - 1
    @data[k] = [a, MIN_VALUE]
    while k > 0
      k = (k - 1) / 2
      @data[k] = (@data[k * 2 + 1] + @data[k * 2 + 2]).sort_by { |a| -a }.take(2)
    end
    nil
  end

  # [a, b)
  # 0-origin
  def query(a, b)
    execute_query(a, b, 0, 0, @size)
  end

  private

  def execute_query(a, b, k, l, r)
    return [MIN_VALUE, MIN_VALUE] if r <= a || b <= l
    return @data[k] if a <= l && r <= b
    vl = execute_query(a, b, k * 2 + 1, l, (l + r) / 2)
    vr = execute_query(a, b, k * 2 + 2, (l + r) / 2, r)
    (vl + vr).sort_by { |a| -a }.take(2)
  end
end

N = gets.to_i
ps = gets.split.map(&:to_i)

st = SegmentTree.new(N)
ps.each.with_index { |p, i| st.update(i, p) }
ans = 0
(0...(N - 1)).each do |i|
  ((i + 1)...N).each do |j|
    ans += st.query(i, j + 1)[1]
  end
end
puts ans
