From cbce3216373ae756eb60c75d54faa5d890aca168 Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Thu, 25 Apr 2024 21:38:20 -0700 Subject: [PATCH] two-pointers: most water contained --- container_with_most_water/Cargo.toml | 6 ++++++ container_with_most_water/src/main.rs | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 container_with_most_water/Cargo.toml create mode 100644 container_with_most_water/src/main.rs diff --git a/container_with_most_water/Cargo.toml b/container_with_most_water/Cargo.toml new file mode 100644 index 0000000..126e474 --- /dev/null +++ b/container_with_most_water/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "container_with_most_water" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/container_with_most_water/src/main.rs b/container_with_most_water/src/main.rs new file mode 100644 index 0000000..5d05aa9 --- /dev/null +++ b/container_with_most_water/src/main.rs @@ -0,0 +1,22 @@ +fn main() { + let res = foo(&[1, 8, 6, 2, 5, 4, 8, 3, 7]); + dbg!(res); +} + +fn foo(height: &[i32]) -> i32 { + let mut left = 0; + let mut right = height.len() - 1; + let mut max = 0; + while left < right { + let lv = height[left]; + let rv = height[right]; + let area = (right - left) * lv.min(rv) as usize; + max = max.max(area); + if lv <= rv { + left += 1; + } else { + right -= 1; + } + } + max as i32 +}