#include <bits/stdc++.h>
using namespace std;

const int N = 3e4 + 7;
int maxLeft[N] = {}, maxRight[N] = {};

int trapWater(vector<int>& heights) {
    int heightsSize = heights.size();
    int totalWater = 0; // Variable to store the total trapped water
	
	maxLeft[0] = heights[0];
	maxRight[heightsSize - 1] = heights[heightsSize - 1];
	for (int i = 1; i < heightsSize; i++)
		maxLeft[i] = max(maxLeft[i - 1], heights[i]);
	for (int i = heightsSize - 2; i >= 0; i--)
		maxRight[i] = max(maxRight[i + 1], heights[i]);

    for(int i = 0; i < heightsSize; i++) {

        // Calculate the trapped water at the current position
        totalWater += min(maxLeft[i], maxRight[i]) - heights[i];
    }

    return totalWater;
}

int main() {
	int n; cin >> n;
	vector<int> heights(n);
	for(int& height : heights) cin >> height;
	cout << trapWater(heights);
	
	return 0;
}