【leetcode】Container with most water--python实现

题目

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 个隔板,让你往里面加水,每个隔板的高度是ai让你找两个隔板,使得他们之间最大面积,问你最大的面积是多少。
设两个隔板的标号分别为 i,j ,那么面积是 min(ai,aj)(ji) i<j ,假设我们找到的 i,j 就是最大的
如果说 i 的左边有一个a1i>ai还大,那么肯定 min(a1i,aj)(ji1)>min(ai,aj)(ji) 和i,j是已知最优的隔板矛盾,
换句话说如果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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值