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.

解题方法

这一题跟trapping water不同,比较简单,因为它只需要找到两条竖边,然后跟x轴组成一个container,计算这个square的面积即可。 而面积是由最小的高度和两条边x轴的差决定的,用two pointer的方法从两边往中间扫就可以,每当计算完一个area的时候就将 高度小的那条边前进一个index。

Solution

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

        return maxArea

Reference