#include<bits/stdc++.h>
using namespace std;
int main(){
int n,a[300001],b[300001],ans=0;
cin>>n;
for(int i=0;i<n;i++)cin>>a[i];
for(int i=0;i<n;i++)b[i]=max(a[i],a[n-1-i])-a[i];
for(int i=1;i<n;i++)if(b[i]>b[i-1])ans+=b[i]-b[i-1];
cout<<b[0]+ans;
return 0;
}