42. Trapping Rain Water
Trapping Rain Water
Solution
public class Solution {
public int trap(int[] height) {
if (height.length == 0)
return 0;
int[] left = new int[height.length];
int[] right = new int[height.length];
int max = height[0];
for(int i = 0; i < height.length; i ++) {
left[i] = Math.max(height[i], max);
max = left[i];
}
max = height[height.length - 1];
for(int j = height.length - 1; j >= 0; j --) {
right[j] = Math.max(height[j], max);
max = right[j];
}
int result = 0;
for(int i = 0; i < height.length; i ++) {
int temp = Math.min(left[i], right[i]);
if (temp > height[i])
result += temp - height[i];
}
return result;
}
}Last updated