#include <iostream>
#include <vector>

using namespace std;

int main() {
  long long int n;
  scanf("%lld", &n);
  vector<pair<long long int, long long int>> a;
  long long int last, el;
  scanf("%lld", &last);
  a.push_back({last, 1});
  for (long long int i = 1; i < n; i++) {
    scanf("%lld", &el);
    if (el == last)
      a[a.size() - 1].second++;
    else
      a.push_back({el, 1});
    last = el;
  }
  long long int totalMinus = 0;
  long long int price = 0;
  while (a.back().first > totalMinus) {
    //printf("%d %d\n", totalMinus, price);
    price += (a.back().first - totalMinus) * a.back().second;
    totalMinus += a.back().second;
    a.pop_back();
  }
  printf("%lld\n", price);
}
