#include <bits/stdc++.h>
using namespace std;
const long long MAXN = 5 * 1000 + 7;
long long minCost[2][MAXN];
long long inputArray[MAXN];
vector<long long> inputs;
int main() {
  long long numberOfInput;
  cin >> numberOfInput;
  for (long long i = 1; i <= numberOfInput; ++i) {
    cin >> inputArray[i];
    inputs.push_back(inputArray[i]);
  }
  sort(inputs.begin(), inputs.end());
  inputs.resize(unique(inputs.begin(), inputs.end()) - inputs.begin());
  for (long long i = 0; i < (long long)inputs.size(); ++i) {
    minCost[1][i] = abs(inputArray[0] - inputs[i]);
  }
  for (long long i = 1; i <= numberOfInput; ++i) {
    minCost[i & 1][0] =
        minCost[(i - 1) & 1][0] + abs(inputArray[i] - inputs[0]);
    for (long long j = 1; j < inputs.size(); ++j) {
      minCost[i & 1][j] =
          min(minCost[i & 1][j - 1],
              minCost[(i - 1) & 1][j] + abs(inputArray[i] - inputs[j]));
    }
  }
  cout << minCost[(numberOfInput)&1][(long long)inputs.size() - 1] << endl;
  return 0;
}
