#include <bits/stdc++.h>
using namespace std;
int main(void) {
  int N;
  cin >> N;
  vector<long> A;
  A.resize(N);
  for (auto &e : A) cin >> e;
  vector<long> B;
  B.resize(N);
  for (int i = 0; i < N; i++) {
    for (int j = i + 1; j < N; j++) {
      if (A[i] + B[i] > A[j] + B[j]) {
        B[j] = A[i] + B[i] - A[j];
      }
    }
  }
  long total = 0;
  for (int i = 0; i < N; i++) total += B[i];
  cout << total << endl;
  return 0;
}
