Skip to content

Commit e210b7a

Browse files
committed
Update 42_Trapping_Rain_Water.java
1 parent 83960ed commit e210b7a

File tree

2 files changed

+27
-26
lines changed

2 files changed

+27
-26
lines changed

Stacks/42_Trapping_Rain_Water.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public int trap(int[] height) {
3+
if (height == null || height.length == 0) {
4+
return 0;
5+
}
6+
7+
int result = 0;
8+
Stack<Integer> st = new Stack<>();
9+
10+
for (int i = 0; i < height.length; i++) {
11+
while (!st.isEmpty() && height[i] > height[st.peek()]) {
12+
int idx = st.pop();
13+
14+
if (!st.isEmpty()) {
15+
int leftPillar = st.peek();
16+
int minHeight = Math.min(height[leftPillar], height[i]);
17+
18+
result += (minHeight - height[idx]) * (i - leftPillar - 1);
19+
}
20+
}
21+
22+
st.push(i);
23+
}
24+
25+
return result;
26+
}
27+
}

Two Pointers/42_Trapping_Rain_Water.java

Lines changed: 0 additions & 26 deletions
This file was deleted.

0 commit comments

Comments
 (0)