#include <bits/stdc++.h>
using namespace std;
const int maxn = 50005;
struct tree {
  int l, r, v, dis;
} heap[maxn];
struct Node {
  int r, at;
} w[maxn];
int merge(int a, int b) {
  if (a == 0) return b;
  if (b == 0) return a;
  if (heap[a].v < heap[b].v) swap(a, b);
  heap[a].r = merge(heap[a].r, b);
  if (heap[heap[a].l].dis < heap[heap[a].r].dis) swap(heap[a].l, heap[a].r);
  heap[a].dis = heap[heap[a].r].dis + 1;
  return a;
}
int pop(int a) {
  int l = heap[a].l;
  int r = heap[a].r;
  heap[a].l = heap[a].r = heap[a].dis = 0;
  return merge(l, r);
}
int Fa(int x) {
  if (x > 0) return x;
  return -x;
}
int now[maxn];
int main() {
  int N, i, l, r, num, j;
  long long ans;
  while (scanf("%d", &N) == 1) {
    for (i = 1; i <= N; i++) {
      scanf("%d", &heap[i].v);
      heap[i].l = heap[i].r = heap[i].dis = 0;
    }
    int cnt = 0;
    w[0].r = 0;
    for (i = 1; i <= N; i++) {
      cnt++;
      w[cnt].r = i;
      w[cnt].at = i;
      now[cnt] = 1;
      while (cnt > 1 && heap[w[cnt - 1].at].v > heap[w[cnt].at].v) {
        cnt--;
        l = w[cnt].at;
        r = w[cnt + 1].at;
        w[cnt].at = merge(l, r);
        if ((w[cnt].r - w[cnt - 1].r) % 2 == 1 &&
            (w[cnt + 1].r - w[cnt].r) % 2 == 1) {
          l = heap[w[cnt].at].l;
          r = heap[w[cnt].at].r;
          w[cnt].at = merge(l, r);
          now[cnt]--;
        }
        w[cnt].r = w[cnt + 1].r;
        now[cnt] += now[cnt + 1];
      }
    }
    ans = 0ll;
    for (i = 1; i <= cnt; i++) {
      for (j = w[i - 1].r + 1; j <= w[i].r; j++)
        ans += (long long)Fa(heap[w[i].at].v - heap[j].v);
    }
    cout << ans << endl;
  }
}
