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
.
public class Solution {
public int trap(int[] A) {
if(A.length<=2)return 0;
int [] leftMaxHeight=new int[A.length];
leftMaxHeight[0]=0;
int maxh=A[0],len=A.length;
for(int i=1;i<A.length;i++)
{
leftMaxHeight[i]=maxh;
if(maxh<A[i])maxh=A[i];
}
int right=A[len-1],left,sum=0;
for(int i=len-2;i>0;i--)
{
left=leftMaxHeight[i];
int minh=Math.min(right,left);
if(minh>A[i])sum+=minh-A[i];
if(right<A[i])right=A[i];
}
return sum;
}
}