class Solution {
public:
int trap(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int *leftMax = new int[n + 5];
int *rightMax = new int[n + 5];
for(int i = 0; i < n; i ++)
{
if(i == 0 || A[i] > leftMax[i-1]) leftMax[i] = A[i];
else leftMax[i] = leftMax[i-1];
}
int ans = 0;
for(int i = n-1; i >= 0; i --)
{
if(i == n - 1 || A[i] > rightMax[i+1]) rightMax[i] = A[i];
else rightMax[i] = rightMax[i+1];
int _min = leftMax[i] < rightMax[i] ? leftMax[i] : rightMax[i];
if(_min > A[i]) ans += (_min - A[i]);
}
return ans;
}
};