#include <bits/stdc++.h>   using namespace std;   long long int arr[1000000];   int main() {     int n;     cin >> n;     long long int count = 0;     for (int i = 0; i < n; i++) {       cin >> arr[i];     }     long long int Min = arr[0];     long long int Max = arr[0];     for (int i = 1; i < n; i++) {       if (arr[i] >= arr[i - 1])         Min = Max = arr[i];       else {         int j = i;         long long int mmin = arr[j - 1];         long long int mmax = arr[j - 1];         int c = 0;         while (arr[j - 1] > arr[j]) {           mmin = min(arr[j], mmin);           mmax = max(arr[j], mmax);           j++;           if (j == n) break;           c++;         }         count += mmax - mmin;         i += c;       }     }     cout << count << endl;     return 0;   }   