Skip to content

Commit de99202

Browse files
authored
Update Trapping Rain Water.java
1 parent bbcb43a commit de99202

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

Hard/Trapping Rain Water.java

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
11
class Solution {
2-
public int trap(int[] height) {
2+
public int trap(int[] A) {
3+
Stack<Integer> stack = new Stack<Integer>();
4+
int i = 0;
35
int maxWater = 0;
4-
for (int i=1;i<height.length-1;i++) {
5-
int maxLeft = 0;
6-
int maxRight = 0;
7-
8-
for (int j=i;j<height.length;j++) {
9-
maxRight = Math.max(maxRight, height[j]);
6+
7+
while (i < A.length){
8+
if (stack.isEmpty() || A[i] <= A[stack.peek()]){
9+
stack.push(i++);
1010
}
11-
12-
for (int j=i;j>=0;j--) {
13-
maxLeft = Math.max(maxLeft, height[j]);
11+
else {
12+
int bot = stack.pop();
13+
maxWater += stack.isEmpty() ? 0 :
14+
(Math.min(A[stack.peek()], A[i]) - A[bot]) * (i - stack.peek() - 1);
1415
}
15-
16-
maxWater += Math.min(maxLeft, maxRight) - height[i];
1716
}
1817

1918
return maxWater;

0 commit comments

Comments
 (0)