1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public int trap(int[] height) { int ans = 0; int n = height.length; if(n == 0){ return ans; }
int[] leftMax = new int[n]; leftMax[0] = height[0]; for(int i = 1; i < n; i++){ leftMax[i] = Math.max(leftMax[i-1], height[i]); }
int[] rightMax = new int[n]; rightMax[n-1] = height[n-1]; for(int i = n - 2; i >= 0; i--){ rightMax[i] = Math.max(rightMax[i+1], height[i]); }
for(int i = 0; i < n; i++){ ans = ans + Math.min(leftMax[i], rightMax[i]) - height[i]; } return ans; } }
|