#include<bits/stdc++.h>
using namespace std;
const long long MaxN = 1e5 +5;
long long n,res=0, a[MaxN];
stack<long long> st;
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> n;
    long long mx = LLONG_MIN;
    for (long long i=1; i<=n ;i++)
    {
        cin >> a[i];
        vector<long long> vt;
        while(!st.empty()&&a[i]>a[st.top()])
        {
            vt.push_back(a[st.top()]);
            st.pop();
        }
        vt.push_back(a[i]);
        st.push(i);
        for (long long i=0; i<vt.size()-1; i++)
        {
            res+=vt[i+1]-vt[i];
        }
        mx=max(mx,a[i]);
    }
    vector<long long> vt;
     while(!st.empty()&&mx>a[st.top()])
    {
        vt.push_back(a[st.top()]);
        st.pop();
    }
    vt.push_back(mx);
    for (long long i=0; i<vt.size()-1; i++)
    {
        res+=vt[i+1]-vt[i];

    }
    cout << res;

}
