#include <bits/stdc++.h>

using namespace std;

int main(){

    int n;
    cin >> n;

    int arr[n + 2] = {0};
    for(int i = 1; i<=n; i++){
        cin >> arr[i];
    }

    int ans = 0, sum = 0;
    for(int i = 2; i<n; i++){
        if(arr[i] < arr[i-1]){
            ans = abs(arr[i] - min(arr[i-1] , arr[i+1]));
            sum += ans;
            arr[i] += ans;
        }
    }

    if(arr[n] < arr[n-1]){
        sum += arr[n-1] - arr[n];
        arr[n] = arr[n-1];
    }

    cout << sum;
    
    return 0;
}