pegitan/leetcode/
problem_11.rs1use crate::Solution;
2
3impl Solution {
4 pub fn max_area_naive(height: Vec<i32>) -> i32 {
8 let mut max = 0;
9 for x in height.iter().enumerate() {
10 for y in height.iter().enumerate().filter(|&y| y.0 > x.0) {
11 max = std::cmp::max(max, (y.0 - x.0) as i32 * std::cmp::min(*x.1, *y.1));
12 }
13 }
14 max
15 }
16
17 pub fn max_area_single_pass(height: Vec<i32>) -> i32 {
18 let mut left: usize = 0;
19 let mut right = height.len() - 1;
20 let mut max = 0;
21 while left < right {
22 let left_height = height[left];
23 let right_height = height[right];
24 let width = (right - left) as i32;
25 let area = std::cmp::min(left_height, right_height) * width;
26 max = std::cmp::max(area, max);
27 match left_height.cmp(&right_height) {
28 std::cmp::Ordering::Greater => right -= 1,
29 _ => left += 1,
30 }
31 }
32 max
33 }
34
35 pub fn max_area(height: Vec<i32>) -> i32 {
36 Solution::max_area_naive(height)
37 }
38}
39
40#[test]
41pub fn problem_11_test() {
42 assert_eq!(Solution::max_area(vec![1, 8, 6, 2, 5, 4, 8, 3, 7]), 49);
43 assert_eq!(Solution::max_area(vec![1, 2]), 1);
44 assert_eq!(Solution::max_area(vec![1, 2, 1]), 2);
45}