# 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.](/files/-LpIwwcg8556ORO0r-ER)

**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)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kongchengzhuge.gitbook.io/leetcode/11.-container-with-most-water.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
