#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <functional>
using namespace std;
char buf[10000000], *ptr = buf - 1;
inline int readint(){
int n = 0;
char ch = *++ptr;
while(ch < ‘0‘ || ch > ‘9‘) ch = *++ptr;
while(ch <= ‘9‘ && ch >= ‘0‘){
n = (n << 1) + (n << 3) + ch - ‘0‘;
ch = *++ptr;
}
return n;
}
const int maxn = 2000 + 10, INF = 0x3f3f3f3f;
int a[maxn], b[maxn], f[maxn][maxn], g[maxn][maxn];
int main(){
fread(buf, sizeof(char), sizeof(buf), stdin);
int n = readint();
for(int i = 1; i <= n; i++)
a[i] = b[i] = readint();
sort(b + 1, b + n + 1);
for(int i = 1; i <= n; i++) f[i][0] = INF;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++){
g[i][j] = f[i - 1][j] + abs(a[i] - b[j]);
f[i][j] = min(f[i][j - 1], g[i][j]);
}
int ans = f[n][n];
sort(b + 1, b + n + 1, greater<int>());
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++){
g[i][j] = f[i - 1][j] + abs(a[i] - b[j]);
f[i][j] = min(f[i][j - 1], g[i][j]);
}
ans = min(ans, f[n][n]);
printf("%d\n", ans);
return 0;
}