问题描述:11.盛水最多的容器
给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
 返回容器可以储存的最大水量。
代码:
class Solution {
public:
    int maxArea(vector<int>& height) {
        int left=0;
        int n=height.size();
        int right=n-1;
        int maxcontainer=0;
        while(left<right)
        {
            int size=min(height[left],height[right])*(right-left);
            maxcontainer=max(size,maxcontainer);
            if(height[left]<height[right])
            {
              ++left;
            }
            else
              right--;
        }
        return maxcontainer;
    }
};
 
思路:
双指针,其中size是每次遍历的值,maxcontainer是比较后的目前最大值。利用索引left和right的值决定是left++还是right–,如果left对应的值>right,选择right–,因为希望每次++或者–后能得到更好的结果(贪心)。










