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.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

1

给出一串整数,a1, a2, …, an ,以(i,ai)为点到x轴做垂线。在这些线中,找出两条线,使得他们围成的矩形面积最大。

暴力求解法很简单,但时间不通过,所以这里不说了。然后想了一个提高性能的方法,是这样的:保存当前位置之前最高点那个位置,只要遍历那个最高点位置左侧所有的点(因为最高点在这,右侧只会越来越小),与当前位置所围成的最大面积就是要求的结果。但是时间还是通不过。只能看答案了。

思路:Two Pointer Approach

上面也提到了,这个题目的要求包含了两店重要的潜在说明。第一,组成矩形区域的高由短的那条线决定;第二,距离越远,组成的矩形面积越大。

基于这两点,考虑这样的一个算法:从左右两侧开始遍历,取两端的线围成矩形区域,然后去除短的那一根,并从那个位置向另一端移动,这样每次都可以保证最远距离,高度最大,从而围成的面积最大。然后取遍历过程中的最大值即可。这样的时间复杂度只有O(n)。

Python 代码实现

class Solution:
    def maxArea(self, height: List[int]) -> int:
        l = len(height)
        
        p = [0 for i in range(l)]
        maxHeight = 0
        maxHeightIndex = 0
        maxArea = 0
        
        left = 0
        right = l-1
        maxArea = (right-left) * min(height[left],height[right])
        while (left < right):
            if height[left] < height[right]:
                left+=1
            else:
                right-=1
            # 记录最大值
            maxArea = max(maxArea,(right-left) * min(height[left],height[right]))
        return maxArea
        

THE END.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值