[leetcode] 11. Container With Most Water

[leetcode] 11. Container With Most Water

题目: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 and n is at least 2.

题意:给定多个二元组(i, ai),以(i, 0), (i ,ai)作为一个挡板的起点和终点,多个二元组(i, ai)可以表征多个挡板。在其中选取两个挡板和x轴作为一个容器,求所有容器中容量的最大值。

题解:首先给出选定两个挡板时求容量的公式V(i, j) = min(height[j], height[i]) * (j - i); (i < j)。先判断挡板数,小于2时不能形成容器,返回0。取左右边界两个挡板求第一个容量值。这时候,往中间扫描,为了保证结果正确,应该移动较低的挡板k。往中间寻找下一个比k高的挡板更新答案,最终 i >= j时结束。

代码如下:

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        l = len(height)
        if l < 2: return 0
        i = 0
        j = l - 1;
        Max = min(height[i], height[j]) * (j - i)
        while i < j:
            if height[i] < height[j]:
                while height[i+1] < height[i]:
                    i = i + 1
                i = i + 1
                Max = max(Max, min(height[i], height[j]) * (j - i))
            else:
                while height[j-1] < height[j]:
                    j = j - 1
                j = j - 1
                Max = max(Max, min(height[i], height[j]) * (j - i))
        return Max

Accept:这里写图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值