import qualified Data.IntSet as S
import Data.List
import Data.Maybe

main = do
  n <- readLn
  a <- map read . words <$> getLine
  let f s (x,i) = g l (Just i) + g (Just i) r
        where
          l = S.lookupLT i s
          r = S.lookupGT i s
          g (Just i) (Just j) = x * (r-j) * ((i+1)-(l+1))
            where 
              l = fromMaybe 0 $ S.lookupLT i s
              r = fromMaybe (n+1) $ S.lookupGT j s
          g _ _ = 0
      xs = reverse $ sort $ zip a [1..]
      ss = scanl (flip S.insert) S.empty $ map snd xs
  print $ sum $ zipWith f ss xs