Trapping Rain Water

Question

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.


Analysis

The same principle for the problem Containes with most water.

Solution

public int trap(int[] height) {
        if(height.length<3) return 0;
        int left=0,right=height.length-1;
        int trap=0,maxleft=0,maxright=0;
        while(left<right){
            if(height[left]<=height[right]){
                if(height[left]<maxleft) trap+=maxleft-height[left];
                else                     maxleft=height[left];
                left++;
            }
            else{
                if(height[right]<maxright) trap+=maxright-height[right];
                else                       maxright=height[right];
                right--;
            }
        }
        return trap;
    }

results matching ""

    No results matching ""