#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const double eps = 1e-10;
const int INF = 0x3f3f3f3f;
const long long INFLL = 0x3f3f3f3f3f3f3f3fll;
const int MAXN = 1e6 + 5;
const int mod = 1e9 + 7;
int a[MAXN];
int main() {
  int n;
  cin >> n;
  priority_queue<int> q;
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    q.push(-a[i]);
    q.push(-a[i]);
    ans += a[i] + q.top();
    q.pop();
  }
  printf("%lld\n", ans);
  return 0;
}
