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.
Trapping Rain Water
Example
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
Solution: Keep two pointers, one from start, one from end, and use another two pointers to track the highest block in the left and in the right.
public int trapRainWater(int[] heights) {
if(heights == null || heights.length == 0) {
return 0;
}
int start = 0, end = heights.length - 1;
int leftBar = heights[0], rightBar = heights[heights.length - 1];
int res = 0;
while(start < end) {
if(heights[start] <= heights[end]) {
if(heights[start] <= leftBar) {
res += leftBar - heights[start];
start++;
}
else {
leftBar = heights[start];
}
}
else {
if(heights[end] <= rightBar) {
res += rightBar - heights[end];
end--;
}
else {
rightBar = heights[end];
}
}
}
return res;
}