#include <bits/stdc++.h>
using namespace std;
const int N = 3 * 1e5 + 100;
long long n, a[N], ans;
priority_queue<long long, vector<long long>, greater<long long> > q;
void load() {}
void process() {
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> a[i];
    q.push(a[i]);
    q.push(a[i]);
    ans += (a[i] - q.top());
    q.pop();
  }
  cout << ans;
}
int main() {
  load();
  process();
  return 0;
}
