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