Tuesday, April 28, 2015

[LeetCode] Trapping Rain Water

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 [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. 

Analysis: From the left for each index i, find the next index j whose value is larger than or equal to i, so that the interval between i and j may trap some water. And repeat the procedure from j till end. Do the same from right, but only find the next index whose value is larger than it to avoid duplication.
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;
    }
};