#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9 + 7;
const int maxn = 5005;
const int maxm = 200005;
int n;
long long ans;
priority_queue<int> pq;
int main() {
  ios_base::sync_with_stdio(false);
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int x;
    cin >> x;
    pq.push(x);
    if (x < pq.top()) {
      ans += pq.top() - x;
      pq.pop();
      pq.push(x);
    }
  }
  cout << ans << endl;
  return 0;
}
