two-pointers: most water contained
This commit is contained in:
parent
8789bbba49
commit
cbce321637
2 changed files with 28 additions and 0 deletions
6
container_with_most_water/Cargo.toml
Normal file
6
container_with_most_water/Cargo.toml
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
[package]
|
||||||
|
name = "container_with_most_water"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
22
container_with_most_water/src/main.rs
Normal file
22
container_with_most_water/src/main.rs
Normal file
|
@ -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
|
||||||
|
}
|
Loading…
Reference in a new issue