1 #include<iostream>
2 #include<cstdio>
3 #include<cstdlib>
4 #include<cstring>
5 #include<algorithm>
6 #define N 2007
7 #define inf 100000009
8 using namespace std;
9 int n,ans,a[N],b[N];
10 int c[N][N],f[N][N];
11 bool cmp(int a,int b){return a>b;}
12 int main()
13 {
14 scanf("%d",&n);
15 for(int i=1;i<=n;i++)
16 {
17 scanf("%d",&a[i]);
18 b[i]=a[i];
19 }
20 sort(b+1,b+n+1);
21 for(int i=1;i<=n;i++) f[i][0]=inf;
22 for(int i=1;i<=n;i++)
23 for(int j=1;j<=n;j++)
24 {
25 c[i][j]=f[i-1][j]+abs(b[j]-a[i]);
26 f[i][j]=min(f[i][j-1],c[i][j]);
27 }
28 ans=f[n][n];
29 sort(b+1,b+n+1,cmp);
30 for(int i=1;i<=n;i++)
31 for(int j=1;j<=n;j++)
32 {
33 c[i][j]=f[i-1][j]+abs(b[j]-a[i]);
34 f[i][j]=min(f[i][j-1],c[i][j]);
35 }
36 ans=min(ans,f[n][n]);
37 printf("%d",ans);
38 }