#include <bits/stdc++.h>
using namespace std;
const long long m = 1e9 + 7;
int arr[200007];
int main() {
  int n;
  cin >> n;
  for (int i = 0; i < n; ++i) {
    cin >> arr[i];
  }
  int mx = arr[n - 1];
  int mn = arr[0];
  int cnt = 0;
  int cnt2 = 0;
  for (int i = n - 2; i >= 0; --i) {
    if (arr[i] > mx) {
      cnt += abs(arr[i] - mx);
    } else {
      mx = arr[i];
    }
  }
  for (int i = 1; i < n; ++i) {
    if (arr[i] < mn) {
      cnt2 += abs(mn - arr[i]);
    } else {
      mn = arr[i];
    }
  }
  cout << min(cnt, cnt2) << endl;
  return 0;
}
