LeetCode 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 iis 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 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)不是我们要找的最大的两个点。

综上,贪心算法不会错过最大的两个点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值