File tree Expand file tree Collapse file tree 1 file changed +20
-10
lines changed
src/main/java/g0001_0100/s0042_trapping_rain_water Expand file tree Collapse file tree 1 file changed +20
-10
lines changed Original file line number Diff line number Diff line change 55
66public class Solution {
77 public int trap (int [] height ) {
8- if (height == null || height .length <= 2 ) {
9- return 0 ;
10- }
118 int l = 0 ;
129 int r = height .length - 1 ;
13- int maxL = height [l ];
14- int maxR = height [r ];
1510 int res = 0 ;
11+ int lowerWall = 0 ;
1612 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 ++;
2028 } 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 --;
2333 }
2434 }
2535 return res ;
You can’t perform that action at this time.
0 commit comments