class Solution { public: int trap(vector<int>& height) { int n=height.size(); int Pmax[n], Bmax[n]; int p=0,b=0; for(int i=0;i<n;i++) { Pmax[i]=p; if(height[i]>=p) p=height[i]; } for(int i=n-1;i>=0;i--) { Bmax[i]=b; if(height[i]>=b) b=height[i]; } int ans=0; for(int i=0;i<n;i++) { int Lmin=min(Pmax[i],Bmax[i]); if((Lmin==0)||(height[i]>=Lmin)) { continue; } else { ans+=(Lmin-height[i]); } } return ans; } };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter