#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, ar[200000], arr[200000], sum = 0;
  cin >> n;
  for (int i = 0; i < n; i++) cin >> ar[i];
  for (int i = 0; i < n - 1; i++) {
    if (ar[i] + arr[i - 1] > ar[i + 1])
      arr[i] = ar[i] + arr[i - 1] - ar[i + 1];
    else
      arr[i] = 0;
  }
  for (int i = 0; i < n; i++) sum += arr[i];
  cout << sum;
  return 0;
}
