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