#include <bits/stdc++.h>
const int64_t inf = 0x7fffffffffffffff;
using namespace std;
bool cmp(int i, int j) { return i <= j; }
int64_t mini(int64_t x, int64_t y) { return x < y ? x : y; }
int main() {
  int n = 0;
  while (cin >> n) {
    vector<int64_t> nums;
    int64_t num = 0;
    for (int i = 0; i < n; ++i) {
      cin >> num;
      nums.push_back(num);
    }
    vector<int64_t> discretes = nums;
    sort(discretes.begin(), discretes.end());
    auto it = unique(discretes.begin(), discretes.end());
    int len = distance(discretes.begin(), it);
    vector<vector<int64_t>> dp(2, vector<int64_t>(len, 0));
    for (int j = 0; j < len; ++j) {
      dp[0][j] = abs(discretes[j] - nums[0]);
    }
    for (int i = 1; i < nums.size(); ++i) {
      int64_t minimal = inf;
      for (int j = 0; j < len; ++j) {
        minimal = mini(minimal, dp[(i - 1) % 2][j]);
        dp[i % 2][j] = minimal + abs(discretes[j] - nums[i]);
      }
    }
    int64_t result = inf;
    for (int j = 0; j < len; ++j) {
      result = mini(result, dp[(nums.size() - 1) % 2][j]);
    }
    printf("%I64d\n", result);
  }
  return 0;
}
