# 11. Container With Most Water

## problem description

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 and n is at least 2.

![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.](https://3489563083-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lp1noAUjUFiycZcmiVr%2F-LpIwp4TYo1_W5qgfwod%2F-LpIwwcg8556ORO0r-ER%2Fimage.png?alt=media\&token=9db083de-eed1-4d2a-b0d4-8f8b39a486a9)

**Example:**

```
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
```

## algorithm thought

首先分析如果想装更多的水，我们需要两个柱子隔得越远越好，并且两个柱子中较矮的那根柱子也会决定装水的量。直接暴力法应该是很多人第一次就想到的方法，两个循环，遍历每一种组合。但是这题还有个条件，就是两个隔得越远，更大容量的概率会大很多。其实这里也用到了之前two sum中第二个方法，左右指针法。现在回顾一下two sum双指针法，首先sort数组，然后左右向中间逼近。这里面也用到了一中额外条件，就是数组已经有序，如果和小于target，就将小的变大一点，也就是left++，反之大的减小。

这题我们也定义左右指针，每次都计算容量，最后取最大值。关键是左右指针如何移动。哪边的柱子更小我就移动哪个，因为移动必定导致宽度减小，只有靠高度增高，才有可能提高总容量，所以这样移动不会漏掉最大值

## code

```cpp
class Solution {
public:
    int maxArea(vector<int>& height) {
        int i=0,j=height.size()-1;
        int res=0;
        while(i<j){
            int h=min(height[i],height[j]);
            res=max(res,h*(j-i));
            
            while(height[i]<=h&&i<j)
                ++i;
            while(height[j]<=h&&i<j)
                --j;
        }
        return res;
    }
};
```

## algorithm analysis

这个代码很简单，时间复杂度是O(n)
