//At each point the water filled will be min(lmax,rmax) - height of that point
class Solution {
public int trap(int[] height) {
if(height.length <= 2)
return 0;
int lMax[] = new int[height.length];
int rMax[] = new int[height.length];
int result = 0;
lMax[0] = 0;
int leftMax=height[0];
for(int i=1; i<height.length; i++){
leftMax = Math.max(leftMax, height[i-1]);
lMax[i] = leftMax;
}
lMax[height.length-1] = leftMax;
rMax[height.length-1] = 0;
int rightMax = height[height.length-1];
for(int j=height.length-2; j>=0; j--){
rightMax = Math.max(rightMax, height[j+1]);
rMax[j] = rightMax;
}
rMax[0] = rightMax;
for(int i=0; i<height.length-1; i++){
int water = Math.min(lMax[i], rMax[i]) - height[i];
water = Math.max(water,0);
result += water ;
}
return result;
}
}