#include <bits/stdc++.h>
const double EPS = 1e-9;
const int INT_INF = 1 << 31 - 1;
const long long I64_INF = 1LL << 63 - 1LL;
const double PI = acos(-1.0);
using namespace std;
long long d[2][5010];
vector<int> c;
int a[5010];
int n;
int main() {
  scanf("%d", &n);
  for (int i = 0; i < (int)n; i++) scanf("%d", a + i), c.push_back(a[i]);
  sort(c.begin(), c.end());
  c.resize(unique(c.begin(), c.end()) - c.begin());
  for (int j = 0; j < (int)c.size(); j++) {
    d[0][j] = 1LL * abs(a[0] - c[j]);
    if (j) d[0][j] = min(d[0][j - 1], d[0][j]);
  }
  int id = 1;
  for (int i = 1; i < n; i++) {
    for (int j = 0; j < (int)c.size(); j++) d[id][j] = I64_INF;
    for (int j = 0; j < (int)c.size(); j++) {
      if (j) d[id][j] = min(d[id][j], d[id][j - 1]);
      d[id][j] = min(d[id][j], d[1 - id][j] + 1LL * abs(a[i] - c[j]));
    }
    id = 1 - id;
  }
  cout << d[1 - id][(int)c.size() - 1] << '\n';
  return 0;
}
