# 【LeetCode】 11. Container With Most Water ## 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. > 給予n個非負整數a1~an,代表一個座標點(i,ai)。 > 現在我們畫了n條從(i,ai)到(i,0)的直線。 > 將兩條線和x軸當作一個容器,請找出哪兩條的容量是最大的。 > 提示:你不能傾斜容器,且n最小是2。 ![](https://i.imgur.com/Z27x19E.png) 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. ## Example: ``` Example: Input: [1,8,6,2,5,4,8,3,7] Output: 49 ``` ## Solution * 參考至[這裡](https://leetcode.com/problems/container-with-most-water/discuss/6126/C++-O(n)-solution-with-thought-process-applying-simple-bucket-theory)。 * 從左邊和右邊往中間逼近,左和右誰比較矮,誰就要往中間動一步。 * 每動一步就計算一次容量,記憶最大值。 ### Code ```C++=1 class Solution { public: int maxArea(vector<int>& height) { int ans=0; for(int i = 0,j=(int)height.size()-1;i!=j;height[i]>height[j]?j--:i++) { int temp = min(height[i],height[j])*(j-i); ans = ans>temp?ans:temp; } return ans; } }; ``` ###### tags: `LeetCode` `C++`