###### tags: `LeetCode` `Two Pointer` `Medium` # LeetCode #11 [Container With Most Water](https://leetcode.com/problems/container-with-most-water) ### (Medium) 給你 n 個非負整數 a1,a2,…,an,每個數代表坐標中的一個點 (i, ai) 。在坐標內畫 n 條垂直線,垂直線 i 的兩個端點分別為 (i, ai) 和 (i, 0) 。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。 ![](https://i.imgur.com/ridPT8p.png) --- 使用兩指針分別指向最左/最右, 當左牆高於右牆時, 由於短版效應, 水只會從右邊流出, 因此從右邊開始計算每一格的儲水量, 也就是右牆高度減去該格高度, 直到某格的高度大於左牆高度, 此時狀況反轉, 變為由左開始計算儲水量, 直到左右牆相交。 --- ``` class Solution { public: int maxArea(vector<int>& height) { int left=0, right=height.size()-1, temp, maxvalue=0; while(left<right){ maxvalue=max(maxvalue,min(height[left], height[right])*(right-left)); if(height[left]>=height[right]){ temp=right-1; while(height[temp]<height[right]){temp--;} right=temp; } else{ temp=left+1; while(height[left]>height[temp]){temp++;} left=temp; } } return maxvalue; } }; ```