#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);
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
int main() {
  int n;
  scanf("%d", &n);
  vector<int> a(n);
  for (int i = 0; i < n; ++i) {
    scanf("%d", &a[i]);
  }
  reverse(begin(a), end(a));
  deque<int> q;
  q.push_back(a[0]);
  int 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;
}
