Skip to content

Commit 5aeab51

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

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

Two Pointers/42_Trapping_Rain_Water.java

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,21 @@ public int trap(int[] height) {
55
}
66

77
int water = 0;
8-
int[] leftMax = new int[height.length], rightMax = new int[height.length];
8+
int leftMax = height[0], rightTallest = height[height.length - 1];
9+
int[] leftMaxes = new int[height.length];
910

10-
leftMax[0] = height[0];
11-
rightMax[rightMax.length - 1] = height[height.length - 1];
12-
13-
for (int i = 1; i < height.length; i++) {
14-
leftMax[i] = Math.max(height[i], leftMax[i - 1]);
11+
for (int i = 0; i < height.length; i++) {
12+
leftMax = Math.max(leftMax, height[i]);
13+
leftMaxes[i] = leftMax;
1514
}
1615

17-
for (int i = height.length - 2; i >= 0; i--) {
18-
rightMax[i] = Math.max(height[i], rightMax[i + 1]);
19-
}
16+
for (int i = height.length - 1; i >= 0; i--) {
17+
rightTallest = Math.max(rightTallest, height[i]);
2018

21-
for (int i = 1; i < height.length - 1; i++) {
22-
water += Math.min(leftMax[i], rightMax[i]) - height[i];
19+
int leftTallest = Math.min(rightTallest, leftMaxes[i]);
20+
if (leftTallest > height[i]) {
21+
water += leftTallest - height[i];
22+
}
2323
}
2424

2525
return water;

0 commit comments

Comments
 (0)