#include <iostream>
#include <vector>
#include <algorithm>
#define int long long

using namespace std;

struct bucket
{
	int pos;
	int balls;
};

signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin >> n;
	vector<bucket> arr;
	bucket buff;
	buff.balls = 1;
	cin >> buff.pos;
	arr.push_back(buff);
	for (int i=1;i<n;i++)
	{
		int p;
		cin >> p;
		if (p==arr[arr.size()-1].pos) arr[arr.size()-1].balls++;
		else
		{
			buff.balls = 1;
			buff.pos = p;
			arr.push_back(buff);
		}
	}
	int cost = 0;
	int shift = 0;
	reverse(arr.begin(),arr.end());
	for (auto i:arr)
	{
		if (i.pos-shift>0)
		{
			cost+=i.balls*(i.pos-shift);
			shift+=i.balls;
		}
	}
	cout << cost;
}
