42. Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcosfor contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
public int trap(int[] heights) {
if (heights.length <= 2) {
return 0;
}
int left = 0, right = heights.length - 1, totalArea = 0;
int leftMaxHeight = heights[left], rightMaxHeight = heights[right];
while (left < right) {
if (heights[left] < heights[right]) {
leftMaxHeight = Math.max(leftMaxHeight, heights[++left]);
totalArea += leftMaxHeight - heights[left];
} else {
rightMaxHeight = Math.max(rightMaxHeight, heights[--right]);
totalArea += rightMaxHeight - heights[right];
}
}
return totalArea;
}
Complexity analysis
- Time complexity: O(n)O(n). Single iteration of O(n)O(n).
- Space complexity: O(1)O(1) extra space. Only constant space required for left, right, left_max and right_max.