11. 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.
Note: You may not slant the container.
题意:给定n条线段,第i条线段的两个端点是(i,0)和(i,ai),这n条线段都是垂直于x轴的,选取其中的两条线段,使这两条线段和x轴构成的容器能容纳的水最多。
方法一:两层循环时间复杂度为O(n^2),但肯定会超时
方法二:
参考:http://blog.csdn.net/a83610312/article/details/8548519
容积即面积,它受长和高的影响,当长度减小时候,高必须增长才有可能提升面积,所以从长度最长时开始递减,然后寻找更高的线来更新候补;
假设我们找到能取最大容积的纵线为 i , j (假定i

class Solution(object):
    def maxArea(self, height):
        n=len(height)
        if n<2:
            return 0
        i=0  #左边
        j=n-1  #右边
        con=0  #容积
        while  i<j:
            minline=min(height[i],height[j]) #最小边
            con=max(minline*(j-i),con) 
            if height[i]<=height[j]:
                k=i
                while height[k]<=height[i] and k<j:
                    k+=1
                i=k
            else :
                k=j
                while height[k]<=height[j] and k>i:
                    k-=1
                j=k
        return con
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值