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

Trapping Water

Notes:

  1. Two pointers
  2. Keep the highest one on two sides
  3. Calculate the sum when moving
    public int trap(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }

        int sum = 0;
        int i = 0; 
        int j = height.length-1;
        int left = 0, right = 0;
        while(i < j) {
            if (height[i] < height[j]) {
                if (height[i] < left) {
                    sum += left-height[i];    
                } else {
                    left = height[i];
                }
                i++;
            } else {
                if (height[j] < right) {
                    sum += right-height[j];    
                } else {
                    right = height[j];
                }
                j--;
            }
        }

        return sum;
    }

results matching ""

    No results matching ""