Skip to content

Commit f89cdf9

Browse files
committed
Add initial implementation for Container With Most Water problem
1 parent 6e352f7 commit f89cdf9

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[package]
2+
name = "container_with_most_water"
3+
version = "0.1.0"
4+
edition = "2024"
5+
6+
[dependencies]
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
//
2+
3+
fn main() {
4+
let arr: Vec<i32> = vec![1, 2, 1];
5+
println!(
6+
"Result of '{:?}' vector: {}",
7+
arr.clone(),
8+
Solution::max_area(arr)
9+
);
10+
}
11+
12+
struct Solution;
13+
14+
use std::collections::HashMap;
15+
16+
impl Solution {
17+
pub fn max_area(height: Vec<i32>) -> i32 {
18+
let CACHE: HashMap<((usize, &i32), (usize, &i32)), usize> = HashMap::new();
19+
let mut prod: usize = 0;
20+
21+
height.iter().enumerate().reduce(|a, b| {
22+
let prod_a = Solution::find_max(a, height.clone());
23+
let prod_b = Solution::find_max(b, height.clone());
24+
if prod_a > prod_b {
25+
prod = prod_a;
26+
a
27+
} else {
28+
prod = prod_b;
29+
b
30+
}
31+
});
32+
33+
prod as i32
34+
}
35+
36+
fn find_max(a: (usize, &i32), height: Vec<i32>) -> usize {
37+
let mut prod = 0;
38+
height
39+
.iter()
40+
.enumerate()
41+
.for_each(|s| {
42+
let calc = Solution::calculate(a, s);
43+
if prod <= calc {
44+
prod = calc
45+
}
46+
});
47+
prod
48+
}
49+
50+
fn calculate(
51+
from: (usize, &i32),
52+
to: (usize, &i32),
53+
) -> usize {
54+
let length = if from.0 > to.0 {
55+
(from.0 + 1) - (to.0 + 1)
56+
} else {
57+
(to.0 + 1) - (from.0 + 1)
58+
};
59+
let height = if from.1 < to.1 { from.1 } else { to.1 };
60+
let prod = length * (*height as usize);
61+
prod
62+
}
63+
}

0 commit comments

Comments
 (0)