#include <bits/stdc++.h>
using namespace std;
const long long INF = 0x3f3f3f3f;
const long long MOD = 97;
const double PI = acos(-1.0);
struct P {
  long long val;
  bool operator<(const P x) const& { return val > x.val; }
} p[330100];
priority_queue<P> que;
int main() {
  int n;
  while (cin >> n) {
    while (!que.empty()) que.pop();
    long long ans = 0;
    for (int i = 1; i <= n; ++i) {
      scanf("%lld", &p[i].val);
      if (que.empty())
        que.push(p[i]);
      else {
        P tmp = que.top();
        if (p[i].val <= tmp.val)
          que.push(p[i]);
        else {
          ans += p[i].val - tmp.val;
          que.pop();
          que.push(p[i]);
          que.push(p[i]);
        }
      }
    }
    cout << ans << endl;
  }
}
