【LeetCode数组】11. Container With Most Water

1.审题

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.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

每一个元素表示一个柱子的高度,两个柱子之间能存的水的取决于柱子之间的宽度,以及左右两个边界柱子中较低的那个。题目要求求出最大的面积。

2. 解题思路

思考套路:

  • 暴力求解
  • 有没有最小重复问题
  • 递归
  • 左右夹逼

2.1 暴力求解

两重for循环,计算所有可能,求出最大的面积。

2.2 左右双指针

利用左右夹逼套路,左指针在开始的位置,右指针指向最后的位置,计算面积,更新最大面积。
我们的目标是求最大的面积,最大面积取决于宽度以及最小的柱子的高度。初始状态是宽度最大的时候,但不一定是最大的面积,因为移动指针会使高度变高。
比较左右两个柱子,低的要变高,若低的在左边,左指针向右移动,若低的在右边,右指针往左移动。左指针或者右指针移动一次,更新一次最大面积。

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        max_area = 0
        start, end = 0, len(height) - 1
        while start < end:
            max_area = max(max_area,min(height[start], height[end]) * (end - start))
            if height[start] < height[end]:
                start += 1
            else :
                end -= 1
        return max_area
            
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值