#include <bits/stdc++.h>
using namespace std;
int main() {
  int N;
  priority_queue<int> a;
  cin >> N;
  int ans = 0;
  for (int i = 0; i < N; i++) {
    int x;
    cin >> x;
    if (a.empty()) {
      a.push(x);
      continue;
    }
    if (a.top() > x) ans += a.top() - x;
    a.push(x);
  }
  cout << ans << endl;
}
