#include <bits/stdc++.h>
using namespace std;
const long long N = 5e3 + 5;
long long n, a[N], Min[N], Dp[N];
vector<long long> vc;
void Input() {
  cin >> n;
  for (long long i = 1; i <= n; ++i) cin >> a[i], vc.push_back(a[i]);
  sort((vc).begin(), (vc).end());
}
void Solve() {
  for (long long i = 1; i <= n; ++i) {
    for (long long j = 0; j < vc.size(); ++j) {
      Dp[j] = Min[j] + abs(a[i] - vc[j]);
    }
    Min[0] = Dp[0];
    for (long long j = 1; j < vc.size(); ++j) {
      Min[j] = min(Min[j - 1], Dp[j]);
    }
  }
  cout << *min_element(Dp, Dp + vc.size());
}
int main() {
  if (fopen("trash.inp", "r"))
    freopen("trash.inp", "r", stdin), freopen("trash.out", "w", stdout);
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  Input();
  Solve();
}
