#include <bits/stdc++.h>
using namespace std;
const int N = 5010;
long long n, a[N], dp[2][N], mini[2][N];
vector<long long> v;
int main() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    long long x;
    cin >> x;
    v.push_back(x);
    a[i] = x;
  }
  sort(v.begin(), v.end());
  v.resize(unique(v.begin(), v.end()) - v.begin());
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= v.size(); j++) {
      int r = i % 2;
      dp[r][j] = mini[1 - r][j] + abs(a[i - 1] - v[j - 1]);
      if (j == 1) {
        mini[r][j] = dp[r][j];
      } else
        mini[r][j] = min(dp[r][j], mini[r][j - 1]);
    }
  }
  cout << mini[n % 2][v.size()];
  cin.get();
}
