import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T

main :: IO ()
main = do
  let
    f :: [Int] -> (Int, Int)
    f = foldl step (0, 0)
      where
        step :: (Int, Int) -> Int -> (Int, Int)
        step (s, m) x = (s', m')
          where
            m' = m `max` x :: Int
            d = m' - x :: Int
            s' = s + d :: Int
  n <- unsafeTextToInt <$> T.getLine :: IO Int
  as <- map unsafeTextToInt . T.words <$> T.getLine :: IO [Int]
  print . fst . f $ as

unsafeTextToInt :: T.Text -> Int
unsafeTextToInt s = case T.signed T.decimal s of
  Right (n, _) -> n
{-# INLINE unsafeTextToInt #-}
