#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;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgpjb25zdCBpbnQgTiA9IDNlNCArIDc7CmludCBtYXhMZWZ0W05dID0ge30sIG1heFJpZ2h0W05dID0ge307CgppbnQgdHJhcFdhdGVyKHZlY3RvcjxpbnQ+JiBoZWlnaHRzKSB7CiAgICBpbnQgaGVpZ2h0c1NpemUgPSBoZWlnaHRzLnNpemUoKTsKICAgIGludCB0b3RhbFdhdGVyID0gMDsgLy8gVmFyaWFibGUgdG8gc3RvcmUgdGhlIHRvdGFsIHRyYXBwZWQgd2F0ZXIKCQoJbWF4TGVmdFswXSA9IGhlaWdodHNbMF07CgltYXhSaWdodFtoZWlnaHRzU2l6ZSAtIDFdID0gaGVpZ2h0c1toZWlnaHRzU2l6ZSAtIDFdOwoJZm9yIChpbnQgaSA9IDE7IGkgPCBoZWlnaHRzU2l6ZTsgaSsrKQoJCW1heExlZnRbaV0gPSBtYXgobWF4TGVmdFtpIC0gMV0sIGhlaWdodHNbaV0pOwoJZm9yIChpbnQgaSA9IGhlaWdodHNTaXplIC0gMjsgaSA+PSAwOyBpLS0pCgkJbWF4UmlnaHRbaV0gPSBtYXgobWF4Uml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