#include <bits/stdc++.h>
using namespace std;
priority_queue<int, vector<int>, greater<int> > buy, sell;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n, x, step = 0;
  cin >> n;
  long long ans = 0;
  while (n--) {
    cin >> x;
    if (!sell.empty() && x > sell.top()) {
      ans += x - sell.top();
      if (!buy.empty() && sell.top() > buy.top()) {
        ans += sell.top() - buy.top();
        buy.pop();
        ++step;
      } else {
        buy.push(sell.top());
        sell.pop();
      }
      sell.push(x);
    } else if (!buy.empty() && x > buy.top()) {
      ans += x - buy.top();
      sell.push(x);
      buy.pop();
      ++step;
    } else
      buy.push(x);
  }
  cout << ans << endl;
  return 0;
}
