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

#11 Container With Most Water

2015-06-21 18:24 579 查看
原题链接:https://leetcode.com/problems/container-with-most-water/

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.

Note: You may not slant the container.

int Min(int a, int b) {
return a < b ? a : b;
}
//left,right分别初始化为第一个板和最后一个板,他们依次向中间移动,宽度变小,只有高度变大才有可能使总容量变大;而高度受限于较短板,所以只有移动较短的板才有可能使总容量变大
int maxArea(int* height, int heightSize) {
int left = 0, right = heightSize - 1;
int max = 0;
while(left < right) {
if(max < (right - left) * Min(height[left], height[right]))
max = (right - left) * Min(height[left], height[right]);
if(height[left] < height[right])
++left;
else
--right;
}

return max;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: