#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n;
  cin >> n;
  vector<long long> a(n);
  for (int i = 0; i < n; ++i) cin >> a[i];
  vector<long long> v = a;
  sort(v.begin(), v.end());
  v.resize(unique(v.begin(), v.end()) - v.begin());
  vector<long long> c(v.size(), -1);
  for (int i = 0; i < int(v.size()); ++i) {
    c[i] = abs(v[i] - a[0]);
  }
  for (int i = 1; i < n; ++i) {
    vector<long long> nc(v.size(), -1);
    long long cmn = c[0];
    for (int j = 0; j < int(v.size()); ++j) {
      cmn = min(cmn, c[j]);
      nc[j] = cmn + abs(v[j] - a[i]);
    }
    swap(c, nc);
  }
  long long ans = c[0];
  for (int i = 0; i < int(v.size()); ++i) {
    ans = min(ans, c[i]);
  }
  cout << ans << endl;
}
