您的位置:首页 > 大数据 > 人工智能

11. Container With Most Water

2018-02-23 18:17 288 查看
Given n non-negative integers a1, a2, ..., an, 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.

两边设一个指针,然后计算area,如果height[i] <= height[j],那么i++,因为在这里height[i]是瓶颈,j往里移只会减少面积,不会再增加area。
这是一个贪心的策略,每次取两边围栏最矮的一个推进,希望获取更多的水。
class Solution {
public:
int maxArea(vector<int>& height) {
int res = 0;
int i = 0,j=height.size()-1;
while(i<j){
res = max(res, min(height[i],height[j])*(j-i));
height[i] > height[j]? j--:i++;
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: