leetcode_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!

思路:

动态规划题目

1.从左至右算出每个点的左方的最大值

2.从右至左算出每个点的右方的最大值

3.从左至右循环sum+=min(leftMax[i]+rightMax[i])-arr[i]

4.sum的值就是所能储存的最大水量

代码:

public int trap(List<Integer> height) {
        int count=0;
        if(height==null)
            return 0;
        if(height.size()==0)
            return 0;
        int len=height.size();
        int arrLeft[]=new int[len];
        int arrRight[]=new int[len];
        int max=0;
        int heigh=0;
        for(int i=0;i<len;i++)
        {
            heigh=height.get(i);
            if(heigh>max)
                max=heigh;
            arrLeft[i]=max;
        }
        max=0;
        heigh=0;
        for(int i=len-1;i>=0;i--)
        {
            heigh=height.get(i);
            if(heigh>max)
                max=heigh;
            arrRight[i]=max;
        }
        int newLen=len-1;
        int min=0;
        for(int i=1;i<newLen;i++)
        {
            heigh=height.get(i);
            min=arrLeft[i]<arrRight[i]?arrLeft[i]:arrRight[i];
            if(min>heigh)
                count+=min-heigh;
        }
        return count;
    }


你可能感兴趣的:(LeetCode,water,Rain,Trapping)