题目:
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.
意思是说 给你
n
个隔板,让你往里面加水,每个隔板的高度是
设两个隔板的标号分别为
i,j
,那么面积是
min(ai,aj)∗(j−i)
设
i<j
,假设我们找到的
i,j
就是最大的
如果说
i
的左边有一个
换句话说如果i,j是最优的,那么i的左边不可能有比
ai
大的,j的右边也不可能有比
aj
大的。
根据这条性质,假设任意两个指针i,j我们从首尾,往中间找到比他们大的,然后更新面积。
每次只动比较小的那个指针,因为高度是由最短的边决定的,如果动高的那条边,面积永远只会小不会大。
- 代码如下
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i = 0
if len(height)<=1:
return 0
j = len(height)-1
res = min(height[0],height[j])*(j-i)
while i < j:
h = min(height[i],height[j])
res = max(h*(j-i),res)
if height[i]>height[j]:
j=j-1
else:
i=i+1
return res
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i = 0
if len(height)<=1:
return 0
j = len(height)-1
h = min(height[i],height[j])
res = h*(j-i)
while i < j:
if height[i]<h:
i = i + 1
continue
if height[j]<h:
j = j - 1
continue
h = min(height[i],height[j])
res = max(h*(j-i),res)
if height[i]>height[j]:
j=j-1
else:
i=i+1
return res