#include <bits/stdc++.h>
using namespace std;
int main() {
  int N;
  cin >> N;
  vector<int> vec(N);
  for (int i = 0; i < N; i++) {
    cin >> vec.at(i);
  }
  vector<int> dai(N - 1, 0);
  if (vec.at(0) > vec.at(1)) {
    dai.at(0) = vec.at(0) - vec.at(1);
  }
  for (int j = 0; j < N - 2; j++) {
    if (vec.at(j + 1) + dai.at(j) > vec.at(j + 2)) {
      dai.at(j + 1) = vec.at(j + 1) + dai.at(j) - vec.at(j + 2);
    } else {
      continue;
    }
  }
  int s = 0;
  for (int k = 0; k < N - 1; k++) {
    s += dai.at(k);
  }
  cout << s << endl;
}
