#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const long long inf = 1e18;
const long double pie = acos((long double)-1);
long long dx[] = {1, -1, 0, 0};
long long dy[] = {0, 0, 1, -1};
int32_t main() {
  long long n;
  scanf("%lld", &n);
  vector<long long> a(n);
  for (long long i = 0; i < n; ++i) {
    scanf("%lld", &a[i]);
  }
  reverse(begin(a), end(a));
  deque<long long> q;
  q.push_back(a[0]);
  long long i = 1;
  long long sum = 0;
  while (i < n) {
    if (a[i] >= q.back()) {
      q.push_back(a[i]);
    } else {
      while (!q.empty()) {
        sum += abs(q.back() - q.front());
        q.pop_front();
      }
      q.push_back(a[i]);
    }
    i++;
  }
  if (!q.empty()) {
    while (!q.empty()) {
      sum += abs(q.front() - q.back());
      q.pop_front();
    }
  }
  printf("%lld\n", sum);
  return 0;
}
