Tuesday, February 11, 2014

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

// water volume for each element depends on the "tallest" bar on its left and right sides. 
public class Solution {
    public int trap(int[] A) {
        if(A.length <= 1) return 0;
        int leftMax = A[0];
        int rightMax = 0;
        int sum = 0;
        for(int i = 1; i < A.length - 1; i++){
            rightMax = 0;
            for(int j = i+1; j < A.length; j++){
                if(A[j]>rightMax) rightMax = A[j];   // search for right max
            }
            if(Math.min(leftMax, rightMax) > A[i]){
                sum += (Math.min(leftMax, rightMax) - A[i]);
            }
            if(A[i] > leftMax) leftMax = A[i];     // update left max
        }
        return sum;
    }
}

No comments:

Post a Comment