1. 程式人生 > >Leetcode 11. 盛最多水的容器(Python3)

Leetcode 11. 盛最多水的容器(Python3)

11. 盛最多水的容器

給定 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

 

暴力法:TLE,僅供參考思路

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        res = 0
        for i in range(0,len(height)-1):
            for j in range(i+1,len(height)):
                s = (j-i)*min(height[i],height[j])
                res = max(s,res)
        return res

 

優化:雙指標法

class Solution:
    def maxArea(self, height):
        res = 0
        i,j = 0,len(height)-1
        while j > i:
            s = (j-i)*min(height[j],height[i])
            if height[i] <= height[j]:
                i += 1
            else:
                j -= 1
            res = max(res,s)
        return res