Skip to content

Commit 0dc3f23

Browse files
committed
feat: add trapping rain water solution
1 parent c2f8101 commit 0dc3f23

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/hard/trapping_rain_water.rs

+25-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,31 @@
11
#![allow(dead_code)]
22

33
pub fn trap(height: Vec<i32>) -> i32 {
4-
todo!("Implement trap function")
4+
let mut left = 0;
5+
let mut right = height.len() - 1;
6+
let mut max_capacity = 0;
7+
let mut left_max = 0;
8+
let mut right_max = 0;
9+
10+
while left < right {
11+
if height[left] < height[right] {
12+
if height[left] >= left_max {
13+
left_max = height[left];
14+
} else {
15+
max_capacity += left_max - height[left];
16+
}
17+
left += 1;
18+
} else {
19+
if height[right] >= right_max {
20+
right_max = height[right];
21+
} else {
22+
max_capacity += right_max - height[right];
23+
}
24+
right -= 1;
25+
}
26+
}
27+
28+
return max_capacity;
529
}
630

731
#[cfg(test)]

0 commit comments

Comments
 (0)