42 Trapping Rain Water
1. Question
2. Implementation
class Solution {
public int trap(int[] height) {
if (height == null || height.length <= 1) {
return 0;
}
int left = 0, right = height.length - 1;
int leftMaxHeight = height[left], rightMaxHeight = height[right];
int res = 0;
while (left < right) {
if (height[left] < height[right]) {
++left;
leftMaxHeight = Math.max(leftMaxHeight, height[left]);
res += leftMaxHeight - height[left];
}
else {
--right;
rightMaxHeight = Math.max(rightMaxHeight, height[right]);
res += rightMaxHeight - height[right];
}
}
return res;
}
}3. Time & Space Complexity
Last updated