'use strict'
function main(input) {
  input = input.trim().split('\n')[1].split(' ').map(val => Number(val))
  const length = input.length
  const sorted = [...input].sort((a, b) => b - a)
  let ans = 0

  sorted.forEach((cur, i) => {
    let count = 0
    const diff = cur - (i === length - 1 ? 0 : sorted[i + 1])
    if (diff) {
      let newArray = []
      input.forEach((val, j) => {
        if (val === cur) {
          if (!(j && input[j - 1] === val)) {
            count++
          }
          newArray.push(val - diff)
        } else {
          newArray.push(val)
        }
      })
      ans += count * diff
      input = [...newArray]
    }
  })
  console.log(ans)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
