

import scala.collection.SortedSet

object Main {

  def main(args: Array[String]): Unit = {

    val N = readLine().toInt
    val array = readLine().split(" ").map(_.toInt)

    val ordered = array.zipWithIndex.sortBy(-_._1)


    var answer = 0
    ordered.foldLeft(SortedSet[Int]()){
      case (indexList, (v,i)) => {
        val low = (List(-1,-1) ++ indexList.until(i).takeRight(2)).takeRight(2)
        val high = (indexList.from(i).take(2).toList ++ List(array.length,array.length)).take(2)

        //println(s"${v} : ${i} = " + ((low(1) - low(0)) * (high(0) - i) + (i - low(1)) * (high(1) - high(0))))

        answer += ((low(1) - low(0)) * (high(0) - i) + (i - low(1)) * (high(1) - high(0))) * v
        indexList + i
      }
    } 


    println(answer)
    

  }
}