#include <bits/stdc++.h>
using namespace std;
vector<bool> steve();
long long mod_plus(long long n1, long long n2);
long long mod_multiply(long long n1, long long n2);
void file() {
  freopen("input.txt", "r", stdin);
  freopen("output.txt", "w", stdout);
}
void zuka() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
}
int main() {
  zuka();
  int n;
  cin >> n;
  vector<long long> v(n);
  long long ctr = 0;
  long long mx = 0, mn = 1e10, mp = -1;
  bool asc = true;
  bool flag = true;
  for (int i = 0; i < n; i++) cin >> v[i];
  for (int i = 0; i < n - 1; i++) {
    if (v[i] > v[i + 1]) {
      long long h = mn;
      mx = max(mx, max((long long)v[i], (long long)v[i + 1]));
      mn = min(mn, min((long long)v[i], (long long)v[i + 1]));
      if (mn != h) mp = i;
      asc = false;
    } else {
      if (!asc) {
        ctr += mx - mn;
        v[mp] = mx;
        mx = 0;
        mn = 1e10;
        asc = true;
        flag = false;
        i--;
      }
    }
  }
  if (!asc) ctr += mx - mn;
  cout << ctr;
}
vector<bool> steve() {
  vector<bool> primes(100005, 1);
  for (long long i = 2; i * i <= 100005; i++) {
    if (primes[i]) {
      for (long long j = i * i; j <= 100005; j += i) primes[j] = 0;
    }
  }
  primes[0] = primes[1] = 0;
  return primes;
}
long long mod_plus(long long n1, long long n2) {
  return ((n1 % 1000003) + (n2 % 1000003)) % 1000003;
}
long long mod_multiply(long long n1, long long n2) {
  return ((n1 % 1000003) * (n2 % 1000003)) % 1000003;
}
