#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define f(i,x,n) for (int i = x;i < n;++i)
map<int, int> mp;
int main() {
int n, mx = 0;
scanf("%d", &n);
f(i, 0, n) {
int t;
scanf("%d", &t);
if (t >= mx)mx = t;
else --mp[mx], ++mp[t];
}
int an = 0, k = 0, b = 0;
for (map<int, int> ::iterator it = mp.begin(); it != mp.end(); ++it) {
if (k)an += it->first - b;
k += it->second;
b = it->first;
}
printf("%d", an);
}
I2luY2x1ZGU8c3RkaW8uaD4KI2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKI2RlZmluZSBsbCBsb25nIGxvbmcKI2RlZmluZSBmKGkseCxuKSBmb3IgKGludCBpID0geDtpIDwgbjsrK2kpCiAKbWFwPGludCwgaW50PiBtcDsKIAppbnQgbWFpbigpIHsKCWludCBuLCBteCA9IDA7CglzY2FuZigiJWQiLCAmbik7CglmKGksIDAsIG4pIHsKCQlpbnQgdDsKCQlzY2FuZigiJWQiLCAmdCk7CgkJaWYgKHQgPj0gbXgpbXggPSB0OwoJCWVsc2UgLS1tcFtteF0sICsrbXBbdF07Cgl9CglpbnQgYW4gPSAwLCBrID0gMCwgYiA9IDA7Cglmb3IgKG1hcDxpbnQsIGludD4gOjppdGVyYXRvciBpdCA9IG1wLmJlZ2luKCk7IGl0ICE9IG1wLmVuZCgpOyArK2l0KSB7CgkJaWYgKGspYW4gKz0gaXQtPmZpcnN0IC0gYjsKCQlrICs9IGl0LT5zZWNvbmQ7CgkJYiA9IGl0LT5maXJzdDsKCX0KCXByaW50ZigiJWQiLCBhbik7Cn0g