#include <bits/stdc++.h>
using namespace std;
template <typename... T>
void print1(T... t) {
  ((cout << t << " "), ...);
}
template <typename... T>
void print2(T... t) {
  vector<vector<long long>> ans = {t...};
  for (long long i = 0; i < (long long)ans.size(); i++) {
    if (i != 0)
      cout << "\t\t";
    else
      cout << "\t";
    for (long long j = 0; j < (long long)ans[i].size(); j++) {
      cout << ans[i][j] << " ";
    }
    if (i != (long long)ans.size() - 1) cout << endl;
  }
}
long long solve() {
  long long n;
  cin >> n;
  vector<long long> vec(n);
  for (int i = 0; i < n; i++) cin >> vec[i];
  long long ans = 0;
  long long lastg = n;
  for (int i = n - 1; i > 0; i--) {
    if (vec[i - 1] > vec[i]) {
      ans += (vec[i - 1] - vec[i]) * (lastg - i);
    } else
      lastg = i;
  }
  return ans;
}
int main() {
  cout << setprecision(10);
  ios::sync_with_stdio(0);
  cin.tie(0);
  long long ans = solve();
  cout << ans << endl;
  return 0;
}
