      program answer
        implicit none
        integer :: i,j,N
        integer,allocatable,dimension(:) :: P
        integer,allocatable,dimension(:) :: Q,R,M,T
        integer :: ans
        intrinsic min,max
        ans=0
        read(*,*) N
        allocate(P(N),Q(N),R(N),M(N),T(N))
        do i=1,N
          P(i)=0
          Q(i)=0
          R(i)=0
          M(i)=0
          T(i)=0
        end do
        read(*,*) (P(i),i=1,N)
        do i=2,N
          do j=i,N
            if(i .eq. 2) then
              Q(j) = min(P(j),P(j-1))
              M(j) = max(P(j),P(j-1))
              T(j) = M(j)
              ans=ans+Q(j)
            else if(i .gt. 2) then
              if(P(j) .lt. Q(j-1)) then
                R(j) = Q(j-1)
                T(j) = M(j-1)
              else
                R(j) = min(P(j),M(j-1))
                T(j) = max(P(j),M(j-1))
              end if
              ans=ans+R(j)
            end if
          end do
          if( i .ne. N) then
            do j=i,N
              Q(j)=R(j)
              M(j)=T(j)
            end do
          end if
        end do
        write(*,'(I0)') ans
      end program answer