用Rust刷leetcode第十一題

linghuyichong發表於2020-08-24

Given n non-negative integers a1, a2, …, a~n ~, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: *You may not slant the container and *n is at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

impl Solution {
    pub fn max_area(height: Vec<i32>) -> i32 {
        let mut result: i32 = 0;
        let mut start: usize = 0;
        let mut end: usize = height.len()-1;

        while start < end {
            let start_height = height.get(start).unwrap();
            let end_height = height.get(end).unwrap();
            let h = start_height.min(end_height);
            result = result.max(((end-start) as i32 )*h);

            if start_height < end_height {
                start += 1;
            } else {
                end -= 1;
            }
        }

        return result;
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章