#include <bits/stdc++.h>
using namespace std;
const long long inf = (1ll << 62);
int n, num[5005];
long long dp[2][5005];
vector<int> v;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", num + i), v.push_back(num[i]);
  sort(v.begin(), v.end());
  int m = unique(v.begin(), v.end()) - v.begin();
  v.resize(m);
  dp[0][0] = 0;
  int now = 0;
  for (int i = 1; i <= n; i++) {
    int next = (now ^ 1);
    long long mi = inf;
    for (int j = 0; j < m; j++) {
      mi = min(dp[now][j], mi);
      dp[next][j] = mi + abs(num[i] - v[j]);
    }
    now ^= 1;
  }
  long long ans = inf;
  for (int i = 0; i < m; i++) ans = min(ans, dp[now][i]);
  printf("%I64d\n", ans);
  return 0;
}
