用Rust刷leetcode第十一题

Problem

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.

Example

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

Solution

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 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!