#include <iostream>
#include <cstdio>

using namespace std;

int uphill[200005];
int len; // current length of uphill
int n;
unsigned long long ans = 0;

int main(void){
	cin >> n;
	uphill[0] = 0; len = 1; // the fake first element
	
	for (int i = 0; i <= n; i++){
		int cur;
		if(i < n)
			scanf("%d", &cur);
		else
			cur = 0; // the fake last element
		
		// eliminate everything that's greater than cur from uphill
		while(uphill[len - 1] > cur){
			int last_height = uphill[len - 1];
			while(uphill[len - 1] == last_height) len--;
			ans += last_height - max(cur, uphill[len - 1]);
		}
		uphill[len++] = cur;
	}
	cout << ans << "\n";
}
