Skip to main content

pegitan/leetcode/
problem_11.rs

1use crate::Solution;
2
3impl Solution {
4    //  TODO    ::  This can be refactored to use anonymous function that accepts an iterator that
5    //              is reversible and accepts some additional parameter to determine the correcting factor.
6    //              Or at least we have to rethink how to transform this...
7    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}