#include <bits/stdc++.h>
using namespace std;
const long long int INF = 1e18;
const int inf = 1e9;
const int MOD = 1e9 + 7;
const int nax = 1000000 + 10;
int n, arr[nax];
int main() {
  ios::sync_with_stdio(0);
  multiset<int> set1;
  long long int ans = 0;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int num;
    cin >> num;
    if (set1.empty() == false && *set1.begin() < num) {
      ans += num - *set1.begin();
      set1.insert(num);
      set1.erase(set1.begin());
    }
    set1.insert(num);
  }
  cout << ans;
  return 0;
}
