#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n;
  cin >> n;
  vector<int> v(n), srt(n);
  for (int i = 0; i < n; i++) {
    cin >> v[i];
    srt[i] = v[i];
  }
  sort(srt.begin(), srt.end(), greater<int>());
  long long int ans = 0, tmp = 0, c = 0;
  int i = n - 1;
  while (i > 0) {
    if (v[i] < v[i - 1]) {
      tmp += v[i];
      c++;
    } else {
      ans += c * v[i] - tmp;
      tmp = 0;
      c = 0;
    }
    i--;
  }
  if (tmp != 0) {
    ans += v[0] * c - tmp;
  }
  cout << ans << endl;
  return 0;
}
