From 18e7167ac9395329209c2702e289efd3d596fb8a Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 19 Apr 2024 08:13:18 +0800 Subject: [PATCH] 20240419 Finished --- src/problem/mod.rs | 3 +- src/problem/p42_trapping_rain_water.rs | 42 ++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 src/problem/p42_trapping_rain_water.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 470f9e1..0ec7f6b 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -105,4 +105,5 @@ mod p274_h_index; mod p380_insert_delete_getrandom_o1; mod p238_product_of_array_except_self; mod p134_gas_station; -mod p135_candy; \ No newline at end of file +mod p135_candy; +mod p42_trapping_rain_water; \ No newline at end of file diff --git a/src/problem/p42_trapping_rain_water.rs b/src/problem/p42_trapping_rain_water.rs new file mode 100644 index 0000000..845aac1 --- /dev/null +++ b/src/problem/p42_trapping_rain_water.rs @@ -0,0 +1,42 @@ +/** + * [42] Trapping Rain Water + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn trap(height: Vec) -> i32 { + let length = height.len(); + let mut left_max = vec![height[0]; length]; + let mut right_max = vec![height[length - 1]; length]; + + for i in (1..length) { + left_max[i] = left_max[i - 1].max(height[i]); + } + + for i in (0..length - 1).rev() { + right_max[i] = right_max[i + 1].max(height[i]); + } + + let mut result = 0; + + for i in 0..length { + result += left_max[i].min(right_max[i]) - height[i]; + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_42() { + assert_eq!(6, Solution::trap(vec![0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])); + } +}