import Control.Monad import Control.Monad.Instances main = readLn >>= print . sum . (liftM2 (zipWith min) (scanl1 max) (scanr1 max) >>= zipWith (-))