11. Container With Most Water

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

O(n2)方法:

class Solution(object):
    def maxArea_stupid(self, height):
        max_area = 0
        for i, vi in enumerate(height):
            for j, vj in enumerate(height):
                area = abs(i - j) * min(vi, vj)
                max_area = max(area, max_area)
        return max_area

此方法直接Time Limit Exceeded没有通过。

O(n)方法:

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

此方法AC。

思路:

①: 假设i,j为当前最大面积对应的坐标,那么i左边一定不会有比i更高的线,否则违背了最大面积的假设;同理j也是。

②: 所以取得更大面积的坐标一定在[i, j]的内部,从两头往中间靠拢,优先收缩小的。

你可能感兴趣的:(11. Container With Most Water)