[leetcode] problem 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.

ZqPKdU.png

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.

Example

Input: [0,1,0,2,1,0,1,3,2,1,2,1]

Output: 6

Stack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public int (int[] height) {
int result = 0;
Stack<Integer> stack = new Stack<>();

for (int i = 0; i < height.length; i++) {
while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
int low = height[stack.pop()];

if (stack.isEmpty())
break;

int high = Math.min(height[i], height[stack.peek()]);
result += (high - low) * (i - stack.peek() - 1);
}

stack.push(i);
}

return result;
}

Other

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public int (int[] height) {
int result = 0;
int left = 0;
int right = height.length - 1;

while (left < right) {
int h = Math.min(height[left], height[right]);

if (height[left] == h) {
left++;

while (left < right && height[left] < h)
result += h - height[left++];
}
else {
right--;

while (left < right && height[right] < h)
result += h - height[right--];
}
}

return result;
}