#include <bits/stdc++.h>
using namespace std;
const int MAXN = 300005;
pair<int, int> ST[4 * MAXN];
int v[MAXN];
void build(int node, int lo, int hi) {
  if (lo == hi) {
    ST[node] = make_pair(v[lo], lo);
    return;
  }
  int mid = (lo + hi) >> 1;
  int left = node << 1;
  int right = left + 1;
  build(left, lo, mid);
  build(right, mid + 1, hi);
  ST[node] = max(ST[left], ST[right]);
}
void update(int node, int lo, int hi, int pos, int v) {
  if (pos > hi || pos < lo) return;
  if (lo == hi) {
    ST[node] = make_pair(v, lo);
    return;
  }
  int mid = (lo + hi) >> 1;
  int left = node << 1;
  int right = left + 1;
  update(left, lo, mid, pos, v);
  update(right, mid + 1, hi, pos, v);
  ST[node] = max(ST[left], ST[right]);
}
pair<int, int> query(int node, int lo, int hi, int i, int j) {
  if (lo > j || hi < i) return make_pair(0, 0);
  if (lo >= i && hi <= j) return ST[node];
  int mid = (lo + hi) >> 1;
  int left = node << 1;
  int right = left + 1;
  pair<int, int> p1 = query(left, lo, mid, i, j);
  pair<int, int> p2 = query(right, mid + 1, hi, i, j);
  return max(p1, p2);
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) scanf("%d", &v[i]);
  build(1, 0, n - 1);
  set<pair<int, int> > will_buy;
  long long cost_buy = 0;
  long long sell_tot = 0;
  for (int i = n - 1; i >= 0; i--) {
    int left = i + 1;
    int right = n - 1;
    if (left > right) continue;
    pair<int, int> p = query(1, 0, n - 1, left, right);
    int sell_price = p.first;
    int sell_id = p.second;
    int replace_profit = 0;
    if (!will_buy.empty()) {
      replace_profit = will_buy.rbegin()->first - v[i];
    }
    int buy_profit = sell_price - v[i];
    if (buy_profit <= 0 && replace_profit <= 0) continue;
    if (replace_profit > buy_profit) {
      pair<int, int> worst = *will_buy.rbegin();
      if (worst.first > v[i]) {
        int worst_id = -worst.second;
        int worst_price = worst.first;
        cost_buy -= v[worst_id];
        will_buy.erase(worst);
        will_buy.insert(make_pair(v[i], -i));
        cost_buy += v[i];
        update(1, 0, n - 1, i, 0);
        left = worst_id + 1;
        p = query(1, 0, n - 1, left, right);
        sell_price = p.first;
        sell_id = p.second;
        if (sell_price > worst_price) {
          sell_tot += sell_price;
          cost_buy += worst_price;
          will_buy.insert(worst);
          update(1, 0, n - 1, sell_id, 0);
        } else {
          update(1, 0, n - 1, worst_id, v[worst_id]);
        }
      }
    } else {
      if (sell_price > v[i]) {
        will_buy.insert(make_pair(v[i], -i));
        cost_buy += v[i];
        sell_tot += sell_price;
        update(1, 0, n - 1, sell_id, -1);
        update(1, 0, n - 1, i, 0);
      }
    }
  }
  cout << sell_tot - cost_buy << endl;
  return 0;
}
