---
# System prepended metadata

title: 11. Container With Most Water
tags: [Leetcode, greedy, medium, python, Top 100 Liked Questions]

---

###### tags: `Leetcode` `medium` `greedy` `python` `Top 100 Liked Questions`

# 11. Container With Most Water

## [題目連結:] https://leetcode.com/problems/container-with-most-water/

## 題目:
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

**Notice** that you may not slant the container.

![](https://i.imgur.com/qIUEaRX.png)

**Example 2:**
```
Input: height = [1,1]
Output: 1
```

#### [圖片來源:] https://leetcode.com/problems/container-with-most-water/

## 解題想法:
* 題目為:**求兩邊界柱內的最大容量**
    * 兩pointer指頭與尾:
        * head=0
        * tail=len(height)-1
    * 每次更新最大容量
    * 並greedy，看height[head]、height[tail]邊界誰小，誰就移動

## python:
``` python=
class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        #use two pointer
        #greedy法:比較當前的left與right較小者則移動
        head=0
        tail=len(height)-1
        res=0
        while head<tail:
            res=max(res,min(height[head],height[tail])*(tail-head))
            if height[head]<height[tail]:
                head+=1
            else:
                tail-=1
        return res


if __name__ == '__main__':
    result = Solution()
    height = [1,8,6,2,5,4,8,3,7]
    ans = result.maxArea(height)
    print(ans)
```