Trapping rain water
public class Solution {
public int trapRainWater(int[] heights) {
if (heights == null || heights.length <= 2) {
return 0;
}
int res = 0;
int left = 0;
int right = heights.length-1;
int lmax = heights[left];
int rmax = heights[right];
while (left < right) {
if (lmax < rmax) {
if (left + 1 < heights.length && heights[left+1] < lmax) {
res += lmax - heights[left+1];
}
left++;
lmax = Math.max(lmax, heights[left]);
} else {
if (right - 1 >= 0 && heights[right-1] < rmax) {
res += rmax - heights[right-1];
}
right--;
rmax = Math.max(rmax, heights[right]);
}
}
return res;
}
}