1. 程式人生 > >【Leetcode_總結】11. 盛最多水的容器 - python 11.

【Leetcode_總結】11. 盛最多水的容器 - python 11.

連線:https://leetcode-cn.com/problems/container-with-most-water/description/

Q:

給定 n 個非負整數 a1,a2,...,an,每個數代表座標中的一個點 (iai) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別為 (iai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。

說明:你不能傾斜容器,且 n 的值至少為 2。

圖中垂直線代表輸入陣列 [1,8,6,2,5,4,8,3,7]。在此情況下,容器能夠容納水(表示為藍色部分)的最大值為 49

輸入: [1,8,6,2,5,4,8,3,7]
輸出: 49

思路:首先這是一個數組問題,需要一個遍歷過程獲得面積最大值,因此使用雙指標,遍歷陣列,逐一進行比較,獲取面積最大值,程式碼如下:

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        max_area = 0
        left = 0
        right = len(height)-1
        while(left < right):
            max_area = max(max_area,min(height[left],height[right])*(right-left))
            if height[left] > height[right]:
                right-=1
            else:
                left+=1
        return max_area