#include <bits/stdc++.h>
using namespace std;
int trapWater(vector<int>& heights) {
int heightsSize = heights.size();
int totalWater = 0;
// Array to store the maximum heights to the left and right of each position
vector<int> maximumLeft(heightsSize);
vector<int> maximumRight(heightsSize);
// Precompute the maximum heights to the left of each position
maximumLeft[0] = heights[0];
for(int i = 1; i < heightsSize; i++) {
maximumLeft[i] = max(maximumLeft[i-1], heights[i]);
}
// Precompute the maximum heights to the right of each position
maximumRight[0] = heights[heightsSize - 1];
for(int i = heightsSize - 2; i >= 0; i--) {
maximumRight[i] = max(maximumRight[i+1], heights[i]);
}
// Calculate the trapped water at each position
for(int i = 0; i < heightsSize; i++) {
totalWater += max(0, min(maximumLeft[i], maximumRight[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;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgdHJhcFdhdGVyKHZlY3RvcjxpbnQ+JiBoZWlnaHRzKSB7CiAgICBpbnQgaGVpZ2h0c1NpemUgPSBoZWlnaHRzLnNpemUoKTsKICAgIGludCB0b3RhbFdhdGVyID0gMDsKCiAgICAvLyBBcnJheSB0byBzdG9yZSB0aGUgbWF4aW11bSBoZWlnaHRzIHRvIHRoZSBsZWZ0IGFuZCByaWdodCBvZiBlYWNoIHBvc2l0aW9uCiAgICB2ZWN0b3I8aW50PiBtYXhpbXVtTGVmdChoZWlnaHRzU2l6ZSk7CiAgICB2ZWN0b3I8aW50PiBtYXhpbXVtUmlnaHQoaGVpZ2h0c1NpemUpOwoKICAgIC8vIFByZWNvbXB1dGUgdGhlIG1heGltdW0gaGVpZ2h0cyB0byB0aGUgbGVmdCBvZiBlYWNoIHBvc2l0aW9uCiAgICBtYXhpbXVtTGVmdFswXSA9IGhlaWdodHNbMF07CiAgICBmb3IoaW50IGkgPSAxOyBpIDwgaGVpZ2h0c1NpemU7IGk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