#include <bits/stdc++.h>
using namespace std;
const int mm = 5004;
long long f[mm], ff[mm], dp[mm];
int main() {
  int m;
  while (cin >> m) {
    for (int i = 0; i < m; i++) {
      cin >> f[i];
      ff[i] = f[i];
    }
    sort(f, f + m);
    memset(dp, 0, sizeof(dp));
    for (int i = 0; i < m; i++)
      for (int j = 0; j < m; j++) {
        dp[j] += abs(ff[i] - f[j]);
        dp[j] = j && dp[j] > dp[j - 1] ? dp[j - 1] : dp[j];
      }
    cout << dp[m - 1] << "\n";
  }
}
