#include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 5;
int n;
priority_queue<int> q;
int main() {
  ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  cin >> n;
  long long res = 0;
  for (int i = 1; i <= n; i++) {
    int x;
    cin >> x;
    q.emplace(-x);
    q.emplace(-x);
    res += x + q.top();
    q.pop();
  }
  cout << res << '\n';
  return 0;
}
