#include <bits/stdc++.h>
using namespace std;
inline size_t key(int i, int j) { return (size_t)i << 32 | (unsigned int)j; }
unordered_map<size_t, int> cache;
int rec(vector<int>& prices, int i, int qty) {
  if (cache.find(key(i, qty)) != cache.end()) return cache[key(i, qty)];
  if (i == prices.size()) {
    cache[key(i, qty)] = 0;
  }
  cache[key(i, qty)] = max(rec(prices, i + 1, qty),
                           max(-prices[i] + rec(prices, i + 1, qty + 1),
                               qty > 0 ? prices[i] + rec(prices, i + 1, qty - 1)
                                       : rec(prices, i + 1, qty)));
  return cache[key(i, qty)];
}
int solve(vector<int>& prices) {
  const int MAX_QTY = 1000;
  vector<vector<int>> dp(prices.size() + 1, vector<int>(MAX_QTY + 10, 0));
  for (int i = prices.size() - 1; i >= 0; i--) {
    for (int qty = MAX_QTY; qty >= 0; qty--) {
      int con = dp[i + 1][qty];
      int sell = qty > 0 ? (dp[i + 1][qty - 1] + prices[i]) : dp[i + 1][qty];
      int buy = qty < MAX_QTY ? dp[i + 1][qty + 1] - prices[i] : dp[i + 1][qty];
      dp[i][qty] = max(max(con, sell), buy);
    }
  }
  return dp[0][0];
}
long long solve3(vector<long long>& prices) {
  multiset<long long> s;
  long long ans = 0;
  for (auto n : prices) {
    if (!s.empty() && n > *s.begin()) {
      ans += n - *s.begin();
      s.erase(s.begin());
      s.insert(n);
    }
    s.insert(n);
  }
  return ans;
}
int main() {
  int n;
  cin >> n;
  vector<long long> prices(n);
  for (int i = 0; i < n; i++) cin >> prices[i];
  cout << solve3(prices) << endl;
}
