#include <bits/stdc++.h>
using namespace std;
priority_queue<int> q;
int n, a;
int main() {
  long long ans = 0;
  cin >> n;
  while (n--) {
    scanf("%d", &a);
    ans += a;
    q.push(-a);
    q.push(-a);
    ans += q.top();
    q.pop();
  }
  cout << ans;
  return 0;
}
