Thursday, January 8, 2015

LeetCode 42: 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!
public class Solution {
    public int trap(int[] A) {
        // Suppose the volume of the trapped water in position i is volume(i)
        // volume(i) depends on the most height bar before and after it --- maxLHeight[i] and maxRHeight[i]
        // volume(i) = min{maxLHeight[i], maxRHeight[i]}-A[i] if min{maxLHeight[i], maxRHeight[i]} > A[i]
        int n = A.length;
        
        if (n <= 2)
            return 0;
            
        int volume = 0; // The sum volume of trapped water
        
        int[] maxLHeight = new int[n];
        int[] maxRHeight = new int[n];
        
        for (int i = 1; i < n; i++)
            maxLHeight[i] = Math.max(maxLHeight[i-1], A[i-1]);
            
        for (int i = n-2; i >= 0; i--)
            maxRHeight[i] = Math.max(maxRHeight[i+1], A[i+1]);
            
        for (int i = 0; i < n; i++)
            if (Math.min(maxLHeight[i], maxRHeight[i]) > A[i])
                volume += Math.min(maxLHeight[i], maxRHeight[i]) - A[i];
        
        return volume;
    }
}

No comments:

Post a Comment