Trapping Rain Water
Given n non-negative integers representing an elevation map, compute how much water it can trap after raining.
Example: height = [0,1,0,2,1,0,1,3,2,1,2,1] → Output: 6
Sample Input
—
Sample Output
—
Constraints
- 1 <= n <= 2 * 10^4
- 0 <= height[i] <= 10^5
Test Cases
Case 1
Args: [[0,1,0,2,1,0,1,3,2,1,2,1]]
Expected: 6
Case 2
Args: [[4,2,0,3,2,5]]
Expected: 9
Two Pointers
function trap(height) {
let left = 0, right = height.length - 1;
let leftMax = 0, rightMax = 0, water = 0;
while (left < right) {
if (height[left] < height[right]) {
leftMax = Math.max(leftMax, height[left]);
water += leftMax - height[left];
left++;
} else {
rightMax = Math.max(rightMax, height[right]);
water += rightMax - height[right];
right--;
}
}
return water;
}
Time: O(n) | Space: O(1)
Saved in this browser only. Private to you.