当前位置 : 主页 > 网络编程 > net编程 >

用Rust刷leetcode第十一题

来源:互联网 收集:自由互联 发布时间:2023-09-06
Problem Given n non-negative integers a 1 , a 2 , …, a~n~ , where each represents a point at coordinate ( i , a i ). n vertical lines are drawn such that the two endpoints of line i is at ( i , a i ) and ( i , 0). Find two lines, which to


Problem

Given n non-negative integers a1a2, …, a~n ~, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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第十一题_rust

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


【文章出处:建湖网页制作 http://www.1234xp.com/jianhu.html 处的文章,转载请说明出处】
网友评论