Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2893a41

Browse files
solve: 42. Trapping Rain Water in rustlang
Signed-off-by: rajput-hemant <rajput.hemant2001@gmail.com>
1 parent 2a3db10 commit 2893a41

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /