//Main(`5
//3 3 3 3 3`);

function Main(line) {
  let [firstline, ...data] = line.trim().split("\n");

  const N = Number(firstline);
  data = data[0].split(" ").map(Number);

  let crt = data[0];
  let keep = [];
  let rst = [];
  for (let i = 1; i < data.length; i++) {
    //더 크면
    if (data[i] > crt) {
      while (keep.length > 0) {
        const v = keep.pop();
        rst.push(crt - v);
      }
      crt = data[i];
    }
    if (data[i] < crt) {
      keep.push(data[i]);
    }
  }
  while (keep.length > 0) {
    const v = keep.pop();
    rst.push(crt - v);
  }

  const sum = rst.reduce((acc, crt) => acc + crt, 0);
  console.log(sum);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
