42. Trapping Rain Water

Problem:

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.


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. Thanks Marcos for contributing this image!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

Solutions:

class Solution {
public:
    int trap(vector<int>& height) {
        int ret = 0;
        int leftHeight = 0;
        int rightHeight = 0;
        int left = 0;
        int right = height.size() - 1;
        while (left <= right) {
            if (height[left] <= height[right]) {
                if (leftHeight - height[left] > 0)  ret += leftHeight - height[left];
                leftHeight = max(leftHeight, height[left]);
                ++left;
            } else {
                if (rightHeight - height[right] > 0) {
                    if (rightHeight - height[right] > 0)    ret += rightHeight - height[right];
                }
                rightHeight = max(rightHeight, height[right]);
                --right;
            }
        }

        return ret;

    }
};

Another solution with two pointers

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

        int water = 0;
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

        int left = 0;
        int right = n - 1;
        int boundary = min(height[0], height[n-1]);
        pq.push({height[0], 0});
        pq.push({height[n-1], n-1});

        while (left <= right) {
            int bar;
            if (height[left] <= height[right]) {
                bar = height[left];
                ++left;
            } else {
                bar = height[right];
                --right;
            }

            if (bar < boundary) {
                water += boundary - bar;
            } else {
                boundary = bar;
            }
        }

        return water;

    }
};

results matching ""

    No results matching ""