对某个值height[i]来说,能trapped的最多的water取决于在i之前最高的值lefthighest[i]和在i右边的最高的值righthighest[i](均不包含自身)。
如果min(left,right) > height[i],那么在i这个位置上能trapped的water就是min(left,right) – height[i]。
using namespace std;
class Solution {
public:
int trap(vector<int>& height) {
vector<int> lefthighest(height.size());
vector<int> righthighest(height.size());
int maxheight=0;
int totalarea=0;
for(int i=0;i<height.size();i++)
{
lefthighest[i]=maxheight;
maxheight=maxheight>height[i]?maxheight:height[i];
}
maxheight=0;
for(int i=height.size()-1;i>=0;i--)
{
righthighest[i]=maxheight;
maxheight=maxheight>height[i]?maxheight:height[i];
}
for(int i=0;i<height.size();i++)
{
int area=min(lefthighest[i],righthighest[i])-height[i];
if(area>0)
{
totalarea+=area;
}
}
return totalarea;
}
};