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 and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7] Output: 49
这道题实际上是一道动态规划问题,我们取左右两个指针i,j置于数组的左右两端。考虑初始状态时宽度最大,i=0,j=n-1。之后向n-1宽度扩展,有两个状态,i=0,j=n-2和i=1,j=n-1。之后再进一步细分状态。
但是本题只需返回最大值,不用记录中间状态,同时本题用了一个小技巧来精简动态规划。还是从最宽的时候出发,当向内拓展的时候,宽度缩小了,但是还想让容积变大,只有让高度增加了容积才可能变大,所以我们将height[i],height[j]中较小的那一个向中间移,这样省去了很多状态的计算。
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
maxw=0
i=0
j=len(height)-1
while i<j:
tmp=min(height[i],height[j])*(j-i)
maxw=max(maxw,tmp)
if height[i]<height[j]:
i+=1
else:
j=j-1
return maxw