#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long n;
  cin >> n;
  long long arr[n];
  for (long long i = (n)-1; i >= 0; i--) cin >> arr[i];
  long long res = 0;
  for (long long i = 0, j = 0; i < n; i = j) {
    j = i + 1;
    while (j < n && arr[j] < arr[i]) {
      if (arr[j] > arr[j - 1]) res += (arr[j] - arr[j - 1]);
      j++;
    }
    res += (arr[i] - arr[j - 1]);
  }
  cout << res << endl;
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t;
  t = 1;
  while (t--) solve();
}
