#include <bits/stdc++.h>
using namespace std;
long long v[200005];
int main() {
  long long n, i;
  cin >> n;
  for (i = 0; i < n; i++) cin >> v[i];
  long long vt = n - 1, res = 0;
  for (i = n - 1; i > 0; i--) {
    if (v[i] < v[i - 1])
      res += (v[i - 1] - v[i]) * (vt - i + 1);
    else
      vt = i - 1;
  }
  cout << res;
}
