#include <bits/stdc++.h>
using namespace std;
int trap(vector<int>& height) {
vector<int> v1;
vector<int> v2;
int n=height.size();
int maxl=0,maxr=0;
for(int i=0;i<n;i++){
if(height[i]>=maxl){
maxl=height[i];
}
v1.push_back(maxl);
}
for(int i=n-1;i>=0;i--){
if(maxr<=height[i]){
maxr=height[i];
}
v2.push_back(maxr);
}
reverse(v2.begin(),v2.end());
for(int i=0;i<n;i++){
v1[i]=min(v1[i],v2[i]);
}
int ans=0;
for(int i=0;i<n;i++){
int p=v1[i]-height[i];
// int p=5;
if(p>0) {
ans+=p;
p=0;
}
ans+=p;
}
return ans;
}
int main()
{
int n;
cin>>n;
vector<int> height;
for(int i=0;i<n;i++){
int a;
cin>>a;
height.push_back(a);
}
cout<<trap(height);
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: