#include <bits/stdc++.h>
using namespace std;
int n, arr[5009];
long long b[5009], bb[5009];
long long dp[3][5009];
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> arr[i];
    bb[i] = arr[i];
  }
  sort(bb + 1, bb + n + 1);
  int k = 2;
  b[1] = bb[1];
  for (int i = 2; i <= n; i++) {
    if (bb[i] != bb[i - 1]) {
      b[k++] = bb[i];
    }
  }
  for (int i = 1; i <= n; i++) {
    dp[1][0] = 100000000000000009ll;
    for (int j = 1; j < k; j++) {
      dp[1][j] = min(dp[0][j] + abs(arr[i] - b[j]), dp[1][j - 1]);
    }
    for (int j = 0; j < k; j++) {
      dp[0][j] = dp[1][j];
      dp[1][j] = 0;
    }
  }
  cout << dp[0][k - 1] << endl;
}
