【leetcode】Container With Most Water

題目描述:

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.spa

解題思路:

這道題說白了就是選兩個值中較小的一個\(min(a_i,a_j)\),而後乘以他們之間的間距\((i-j)\)的最大值.最簡單的\(O(n^2)\)的遍歷。可是咱們能夠採起貪心的算法,從兩端開始不斷選擇較大的一側組成新的container。code

class Solution:
    # @return an integer
    def maxArea(self, height):
        res = 0 
        l = len(height)
        i = 0
        j = l-1
        while i < j:
            t = min(height[i], height[j]) * (j-i)
            if t > res:
                res = t
            if height[i] < height[j]:
                i += 1
            else:
                j -= 1            
        return res
相關文章
相關標籤/搜索