leetcode 011 Container With Most Water

14 篇文章 0 订阅

leetcode 011 Container With Most Water

第6天

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的杆的高度height(i) 求出任意两个杆和x轴围城的水桶装水最多是多少

看题意 定义两个pointer i指左边的杆 j指右边的杆

在 j 的右端没有一条线会比它高! 假设存在 k | ( j < k && ak > aj) ,那么 由 ak> aj,所以 min( ai,aj, ak) =min(ai,aj) ,所以由i, k构成的容器的容积C’ = min(ai,aj ) * ( k-i) > C,与C是最值矛盾,所以得证j的后边不会有比它还高的线;

同理 i的左边也是一样 所以最大的容积只能在[i,j]里面 并且 最低高度得到提升

容积 = 宽 * 高 宽变小 高变大的时候 有可能增加容积 从短的那一段往里 挪- -

代码

class Solution:
    # @param {integer[]} height
    # @return {integer}
    def maxArea(self, height):
        lens = len(height)
        i = 0
        j = lens - 1
        ans = 0
        while j > i :
            ans = max(min(height[i],height[j])*(j-i),ans)
            if height[i] > height[j]:
                j = j - 1
            else:
                i = i + 1
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值