天天看點

用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.

用Rust刷leetcode第十一題

Example

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;
    }
}