/
TrappingRainWater.java
47 lines (43 loc) · 1.22 KB
/
TrappingRainWater.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// https://leetcode.com/problems/trapping-rain-water
class Solution {
public int trap(int[] height) {
Stack<Integer> stack = new Stack<>();
int sum = 0, max = 0;
for (int x : height) {
if (stack.isEmpty()) {
stack.push(x);
max = x;
} else {
if (x < max) {
stack.push(x);
} else {
while (!stack.isEmpty()) {
sum += max - stack.pop();
}
max = x;
stack.push(x);
}
}
}
Stack<Integer> another = new Stack<>();
max = 0;
while (!stack.isEmpty()) {
int x = stack.pop();
if (another.isEmpty()) {
max = x;
another.push(x);
} else {
if (x < max) {
another.push(x);
} else {
while (!another.isEmpty()) {
sum += max - another.pop();
}
max = x;
another.push(x);
}
}
}
return sum;
}
}