题目: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 iis 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.
先上代码:
class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i=0
j=len(height)-1
res=0
while i<=j:
res=max(res,min(height[i],height[j])*(j-i))
if height[i]>=height[j]:
j=j-1
else:
i=i+1
return res
现在证明这样操作不会错过能装最多的水的两个点。假设最终要找的两个点的坐标为p,q(即假设:min(height[p],height[q])*(q-p)为我们要找的最大值)
……,p-1,p,……,q-1,q,…
假设现在进行的对比的两个索引分别为(p-1,q),现在分情况进行讨论:
1.如果height[p-1]<height[q],则下一个要进行计算的两个点的索引分别为(p,q),则不会错过最大值点。
2.如果height[p-1]>=height[q],则下一个要进行计算的两个点的索引分别为(p-1,q-1),错过了(p,q)两个点。现在我们来比较height[p-1]和height[p]的大小关系。
(1)如果height[p-1]>height[p]>=height[q],则min(height[p-1],height[q])*(q-p+1)>min(height[p]-height[q])*(p-q),此时,(p,q)不是我们要找的两个点,与假设矛盾。
(2)如果height[p-1]>height[q]>height[p], 同上,仍然可以证明(p,q)不是我们要找的两个点。
(3)当height[p]>=height[p-1]时,仍然可以证明(p,q)不是我们要找的最大的两个点。
综上,贪心算法不会错过最大的两个点。