42. Trapping Rain Water

class Solution {
public:
    int trap(vector<int>& height) {
        int res = 0;
        int n = height.size();
        if (n == 0)return 0;
        vector<int> fromLeft(n), fromRight(n);

        fromLeft[0] = height[0];
        fromRight[n - 1] = height[n - 1];
        for (int i = 1; i < n; i++)
            fromLeft[i] = max(fromLeft[i - 1], height[i]);
        for (int i = n - 2; i >= 0; i--)
            fromRight[i] = max(fromRight[i + 1], height[i]);


        // for (int i = 0; i < n; i++)cout<<fromLeft[i]<<' ';cout<<endl;
        // for (int i = 0; i < n; i++)cout<<fromRight[i]<<' ';cout<<endl;

        for (int i = 1; i < n - 1; i++)
            res += max(0, min(fromLeft[i - 1], fromRight[i + 1]) - height[i]);
                      //pay attention the difference can be negative!!!!

        return res;
    }
};

a more beautiful O(1) space one

class Solution {
public:
    int trap(vector<int>& height) {
        int res = 0;
        int n = height.size();
        int l = 0, r = n - 1;
        int maxLeft = 0, maxRight = 0;

        while(l < r) {
            maxLeft = max(maxLeft, height[l]);
            maxRight = max(maxRight, height[r]);
            if (maxLeft < maxRight) {
                res += maxLeft - height[l];
                l++;
            } else {
                res += maxRight - height[r];
                r--;
            }
        }

        return res;
    }
};

results matching ""

    No results matching ""