#include <bits/stdc++.h>
using namespace std;
vector<int> v, vc;
vector<vector<long long> > dp;
int n;
bool state;
inline int dist(int x, int y) { return abs(x - y); }
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> n;
  v.resize(n);
  for (int& x : v) cin >> x;
  vc = v;
  sort(vc.begin(), vc.end());
  dp.resize(2, vector<long long>(n));
  for (int i = 0; i < n; i++) {
    dp[state][i] = dist(v[0], vc[i]);
  }
  for (int i = 1; i < n; i++) {
    state = !state;
    dp[state][0] = dp[!state][0] + dist(v[i], vc[0]);
    for (int j = 1; j < n; j++) {
      dp[state][j] =
          min(dp[!state][j] + dist(v[i], vc[j]),
              dp[state][j - 1] + dist(v[i], vc[j]) - dist(v[i], vc[j - 1]));
    }
  }
  cout << *min_element(dp[state].begin(), dp[state].end());
}
