#include <bits/stdc++.h>
int main() {
  int n;
  int* a;
  int* b;
  scanf("%d", &n);
  a = (int*)malloc(n * sizeof(int));
  b = (int*)malloc(n * sizeof(int));
  for (int i = 0; i != n; i++) {
    scanf("%d", &a[i]);
  }
  b[0] = 0;
  for (int i = 1; i != n; i++) {
    if (a[i] <= b[i - 1] + a[i - 1]) {
      b[i] = (b[i - 1] + a[i - 1]) - a[i];
    } else {
      b[i] = 0;
    }
  }
  unsigned int c = 0;
  for (int i = 0; i != n; i++) {
    c += b[i];
  }
  printf("%u", c);
  return 0;
}
