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.

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
class Solution {
    // O(N) Space
    public int trap(int[] height) {
        int maxLeft[] = new int[height.length];
        for (int i = 0; i < height.length; i++) {
            if (i == 0)
                maxLeft[i] = height[i];
            else
                maxLeft[i] = Math.max(height[i], maxLeft[i - 1]);
        }

        int[] maxRight = new int[height.length];
        for (int i = height.length - 1; i >= 0; i--) {
            if (i == height.length - 1)
                maxRight[i] = height[i];
            else
                maxRight[i] = Math.max(height[i], maxRight[i + 1]);
        }

        int sum = 0;
        for (int i = 0; i < height.length; i++) {
            // Now for every wall, we are finding the max wall on it's right & left (including itself)
            // Now the water above this wall can be the min(maxleft,maxright)
            int minWall = Math.min(maxLeft[i], maxRight[i]);
            sum += minWall - height[i];
        }
        return sum;
    }
    // O(1) Space
    // https://drive.google.com/file/d/1wvPyepc1cw2IPgtK9TmjjBzSIB6uVy8t/view?usp=sharing
}

Last updated