Skip to content

Commit 4662c79

Browse files
authored
Create 0042_Trapping_Rain_Water.java
1 parent 2cc6fc0 commit 4662c79

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Diff for: 0042_Trapping_Rain_Water.java

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// id: 42
2+
// Name: Trapping Rain Water
3+
// link: https://leetcode.com/problems/trapping-rain-water/description/
4+
// Difficulty: Hard
5+
6+
class Solution {
7+
public int trap(int[] height) {
8+
int n = height.length;
9+
int [] rightMaxes = new int[n]; // maximum height at right of index i
10+
rightMaxes[n-1] = 0; // no element right
11+
12+
for (int i = n-2; i >= 0; i--) {
13+
rightMaxes[i] = Math.max(height[i+1], rightMaxes[i+1]);
14+
}
15+
16+
17+
int result = 0;
18+
int leftMax = height[0];
19+
for (int i = 1; i < height.length-1; i++) {
20+
// max right, max left
21+
int current = Math.min(rightMaxes[i], leftMax) - height[i];
22+
23+
if (current > 0) result += current;
24+
25+
leftMax = Math.max(leftMax, height[i]);
26+
}
27+
28+
return result;
29+
}
30+
}

0 commit comments

Comments
 (0)