#include <bits/stdc++.h>
#define ¹ first
#define ² second
int main(){
	long n, i, a, b{0}, c{0}, d{0};
	std::cin >> n;
	std::vector<std::pair<long, long>> A;
	for(i = 0; i < n; ++i){
		std::cin >> a;
		if(a == b) ++A.back().²;
		else A.emplace_back(a, 1);
		b = a;
	}
	for(auto z = A.rbegin(); z != A.rend(); ++z){
		if(z -> ¹ <= d) break;
		c += (z -> ¹ - d) * z -> ²;
		d += z -> ²;
	}
	std::cout << c << "\n";
}
