File tree 1 file changed +20
-10
lines changed
src/main/java/g0001_0100/s0042_trapping_rain_water
1 file changed +20
-10
lines changed Original file line number Diff line number Diff line change 5
5
6
6
public class Solution {
7
7
public int trap (int [] height ) {
8
- if (height == null || height .length <= 2 ) {
9
- return 0 ;
10
- }
11
8
int l = 0 ;
12
9
int r = height .length - 1 ;
13
- int maxL = height [l ];
14
- int maxR = height [r ];
15
10
int res = 0 ;
11
+ int lowerWall = 0 ;
16
12
while (l < r ) {
17
- if (maxL < maxR ) {
18
- maxL = Math .max (height [++l ], maxL );
19
- res += maxL - height [l ];
13
+ int lVal = height [l ];
14
+ int rVal = height [r ];
15
+ // If left is smaller than right ptr, make the lower wall the bigger of lVal and its
16
+ // current size
17
+ if (lVal < rVal ) {
18
+ // If lVal has gone up, move the lowerWall upp
19
+ lowerWall = Math .max (lVal , lowerWall );
20
+ // Add the water level at current point
21
+ // Calculate this by taking the current value and subtracting it from the lower wall
22
+ // size
23
+ // We know that this is the lower wall because we've already determined that lVal <
24
+ // rVal
25
+ res += lowerWall - lVal ;
26
+ // Move left ptr along
27
+ l ++;
20
28
} else {
21
- maxR = Math .max (height [--r ], maxR );
22
- res += maxR - height [r ];
29
+ // Do the same thing, except now we know that the lowerWall is the right side.
30
+ lowerWall = Math .max (rVal , lowerWall );
31
+ res += lowerWall - rVal ;
32
+ r --;
23
33
}
24
34
}
25
35
return res ;
You can’t perform that action at this time.
0 commit comments