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

解题思路:

这道题说白了就是选两个值中较小的一个(min(a_i,a_j)),然后乘以他们之间的间距((i-j))的最大值.最简单的(O(n^2))的遍历。但是我们可以采取贪心的算法,从两端开始不断选择较大的一侧组成新的container。

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
原文地址:https://www.cnblogs.com/MrLJC/p/4277033.html