Trapping Rain Water
LintCode-363.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.
Example: Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
Challenge:
O(n) time and O(1) memory
O(n) time and O(n) memory is also acceptable.
public class Solution {
/**
* @param heights: an array of integers
* @return: a integer
*/
public int trapRainWater(int[] heights) {
if (heights == null || heights.length == 0) {
return 0;
}
int[] left = new int[heights.length];
left[0] = heights[0];
for (int i = 1; i < heights.length; i++) {
left[i] = Math.max(left[i - 1], heights[i]);
}
int[] right = new int[heights.length];
right[heights.length - 1] = heights[heights.length - 1];
for (int i = heights.length - 2; i >= 0; i--) {
right[i] = Math.max(right[i + 1], heights[i]);
}
int sum = 0;
for (int i = 0; i < heights.length; i++) {
int min = Math.min(left[i], right[i]);
if (min - heights[i] > 0) {
sum += min - heights[i];
}
}
return sum;
}
}
Hope this helps,
Michael