DAY6:leetcode #11 Container With Most Water

本文探讨了如何优化双指针算法解决“容器容量最大化”问题,通过实例展示了算法的改进过程,旨在提高解决方案的效率。利用双指针技术在O(n)时间内寻找最优解,适用于数组中求解特定条件下的最大值问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

一开始用了两层循环遍历的思路,超时。看到了这样的思路:采用两个指针l和r,初始化分别指向数组的两端,然后在向中间移动找到最大容量。如果l指向的数字小,则l需要右移才有可能获得更大容量,因为此时如果左移r,得到的容量肯定比左移r之前的容量小(高度已经被较小的l限制住了)。如果r指向的数字小,则需要左移r。这样,当l和r相遇的时候,最大的容量就是我们需要的。

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        max_v = 0
        i = 0
        j = len(height) - 1
        while True:
            if max_v < (j-i)*min(height[i],height[j]):
                max_v = (j-i)*min(height[i],height[j])
            if height[i] < height[j]:
                i += 1
            else:
                j -= 1
            if i == j:
                break
        return max_v
                


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值