1 #include<cstdio>
2 #include<cstring>
3 #include<algorithm>
4 #include<iostream>
5 #define mem(a,b) memset(a,b,sizeof(a))
6 using namespace std;
7 const int N=2006;
8 inline int minn(int a,int b){return a<b?a:b;}
9 inline int abss(int x){return x<0?-x:x;}
10 struct son1
11 {
12 int pos,val;
13 friend bool operator < (const son1 &a,const son1 &b)
14 {
15 return a.val<b.val;
16 }
17 };
18 son1 ji[N];
19
20 int n,cnt;
21 int a[N];
22 int ha[N];
23 int minl1,minl2,ans;
24 int f[2066][2066];
25
26 int main(){
27 //freopen("grading.2.in","r",stdin);
28 scanf("%d",&n);
29 for(int i=1;i<=n;++i)
30 {
31 scanf("%d",&ji[i].val);
32 ji[i].pos=i;
33 }
34 sort(ji+1,ji+1+n);
35 ji[0].val=-100;
36 for(int i=1;i<=n;++i)
37 {
38 if(ji[i].val!=ji[i-1].val)
39 ha[++cnt]=ji[i].val;
40 a[ji[i].pos]=cnt;
41 }
42
43 for(int i=1;i<=n;++i)
44 {
45 f[i][0]=0x7fffffff;
46 int minl=0x7fffffff;
47 for(int j=1;j<=cnt;++j)
48 {
49 minl=minn(minl,f[i-1][j]);
50 f[i][j]=minn(f[i][j-1],minl+abss(ha[j]-ha[a[i]]));
51 }
52 }
53
54 minl1=f[n][cnt];
55
56 mem(f,0);
57 for(int i=1;i<=n;++i)
58 {
59 f[i][cnt+1]=0x7fffffff;
60 int minl=0x7fffffff;
61 for(int j=cnt;j>=1;--j)
62 {
63 minl=minn(minl,f[i-1][j]);
64 f[i][j]=minn(f[i][j+1],minl+abss(ha[j]-ha[a[i]]));
65 }
66 }
67
68 minl2=f[n][1];
69
70 printf("%d",minn(minl1,minl2));
71 //while(1);
72 return 0;
73 }