Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given
Given
[0,1,0,2,1,0,1,3,2,1,2,1], return 6.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
class Solution
{
static bool lt(int a, int b){return a>b;}
static bool le(int a, int b){return a>=b;}
int trap(vector<int>& height,
const function <bool (int, int)>& comp)
{
int res =0, i=0, sum=0;
int l = i++;
for(;i<height.size();i++)
{
if(comp(height[i],height[l]))
{
res += max(0,(i-l-1)* height[l]-sum);
l = i;
sum = 0;
}
else sum += height[i];
}
return res;
}
public:
int trap(vector<int>& height)
{
int leftValue = trap(height, le);
reverse(height.begin(), height.end());
int rightValue = trap(height, lt);
return leftValue + rightValue;
}
};