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.
1 public class Solution { 2 public int trap(int[] A) { 3 int len = A.length; 4 if(len<2) return 0; 5 int []leftMax = new int[len], rightMax = new int[len]; 6 int max=0; 7 max = A[0]; 8 leftMax[0] = 0; 9 for(int i=1;imax){12 max = A[i];13 }14 }15 max = A[len-1]; 16 rightMax[len-1]=0;17 int trap = 0;18 for(int i=len-2;i>=0;i--){19 rightMax[i] = max;20 if(max 0){24 trap+=Math.min(rightMax[i],leftMax[i])-A[i];25 }26 }27 return trap;28 }29 }