File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
src/0001-0100/042 - Trapping Rain Water Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ impl Solution {
2
+ pub fn trap ( height : Vec < i32 > ) -> i32 {
3
+ let ( mut left, mut right) = ( 0 , height. len ( ) - 1 ) ;
4
+ let ( mut left_max, mut right_max) = ( 0 , 0 ) ;
5
+ let mut ans = 0 ;
6
+
7
+ // iterate from both sides to the middle
8
+ while left < right {
9
+ // if left is lower than right, then the water level depends on left
10
+ // else the water level depends on right
11
+ if height[ left] < height[ right] {
12
+ // if left height is higher than left_max, then update left_max
13
+ // else add the difference between left_max and left height to ans
14
+ if height[ left] >= left_max {
15
+ left_max = height[ left] ;
16
+ } else {
17
+ ans += left_max - height[ left] ;
18
+ }
19
+ left += 1 ;
20
+ } else {
21
+ // if right height is higher than right_max, then update right_max
22
+ // else add the difference between right_max and right height to ans
23
+ if height[ right] >= right_max {
24
+ right_max = height[ right] ;
25
+ } else {
26
+ ans += right_max - height[ right] ;
27
+ }
28
+ right -= 1 ;
29
+ }
30
+ }
31
+
32
+ ans
33
+ }
34
+ }
You can’t perform that action at this time.
0 commit comments