
正文
[LeetCode 题解]: Container With Most Water
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
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 together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
贪心策略:两端设置围栏,无论如何注水,水只要不超过其中较短的那一根围栏即可,中间的柱子可以忽略。
相继缩短距离,较短一端的柱子换成向里的一根。
例如: height[left] <= height[right] : left = left+1;
反之, right = right-1;
class Solution {
public:
int maxArea(vector<int> &height) {
int ans=,left=,right=height.size()-,contain;
while(left<right)
{
contain = (right-left)*min(height[right],height[left]);
ans = max(contain, ans);
height[left]<=height[right]?left++:right--;
}
return ans;
}
};






