#include <bits/stdc++.h>
using namespace std;
const int N = 5e3 + 5;
int main() {
  ios::sync_with_stdio(0), ios_base::sync_with_stdio(0), cin.tie(0),
      cout.tie(0);
  ;
  int n;
  cin >> n;
  long long ans = 0;
  priority_queue<int> pq;
  while (n--) {
    int x;
    cin >> x;
    pq.push(x);
    if (pq.top() > x) ans += pq.top() - x, pq.pop(), pq.push(x);
  }
  cout << ans << "\n";
  return 0;
}
