#include <bits/stdc++.h>
using namespace std;
int N, sum = 0, back = 0, pre = 0;
long num = 0;
vector<long> A;
int getmax(int a, int b) {
  int max = a;
  if (a > b) {
    max = a;
  } else {
    max = b;
  }
  return max;
}
int main() {
  cin >> N;
  for (int i = 0; i < N; i++) {
    cin >> num;
    A.push_back(num);
  }
  for (int i = 0; i < N; i++) {
    if (i == 0) {
      sum = 0;
      back = A[i];
    } else if (i == 1) {
      pre = A[i];
      if (back > pre) {
        sum += (back - pre);
      }
    } else {
      pre = A[i];
      back = getmax(A[i - 2], A[i - 1]);
      if (back - pre > 0) {
        sum += (back - pre);
        back = pre;
      }
    }
  }
  cout << sum;
  return 0;
}
