Skip to content

Commit 8506741

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 42_Trapping_Rain_Water.java
1 parent 5aeab51 commit 8506741

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

Two Pointers/42_Trapping_Rain_Water.java

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,20 @@ public int trap(int[] height) {
44
return 0;
55
}
66

7+
int leftMax = 0, rightMax = 0;
8+
int left = 0, right = height.length - 1;
79
int water = 0;
8-
int leftMax = height[0], rightTallest = height[height.length - 1];
9-
int[] leftMaxes = new int[height.length];
1010

11-
for (int i = 0; i < height.length; i++) {
12-
leftMax = Math.max(leftMax, height[i]);
13-
leftMaxes[i] = leftMax;
14-
}
15-
16-
for (int i = height.length - 1; i >= 0; i--) {
17-
rightTallest = Math.max(rightTallest, height[i]);
11+
while (left < right) {
12+
leftMax = Math.max(leftMax, height[left]);
13+
rightMax = Math.max(rightMax, height[right]);
1814

19-
int leftTallest = Math.min(rightTallest, leftMaxes[i]);
20-
if (leftTallest > height[i]) {
21-
water += leftTallest - height[i];
15+
if (leftMax < rightMax) {
16+
water += leftMax - height[left];
17+
++left;
18+
} else {
19+
water += rightMax - height[right];
20+
--right;
2221
}
2322
}
2423

0 commit comments

Comments
 (0)