#include <bits/stdc++.h>
using namespace std;
int a[5010];
vector<int> v;
int n;
long long g[5010];
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    v.push_back(a[i]);
  }
  sort(v.begin(), v.end());
  g[0] = abs(a[0] - v[0]);
  for (int i = 1; i < n; i++) g[i] = g[i - 1] + abs(a[i] - v[0]);
  long long ret = g[n - 1];
  for (int j = 1; j < n; j++) {
    g[0] = min(g[0], 1LL * abs(a[0] - v[j]));
    for (int i = 1; i < n; i++) g[i] = min(g[i], g[i - 1] + abs(a[i] - v[j]));
    ret = min(ret, g[n - 1]);
  }
  cout << ret << endl;
}
