11. Container With Most Water

本文介绍了一种算法问题,即给定一系列垂直线段的高度,找出两条线段构成的容器能容纳的最大水量。通过双指针技巧从两端逼近,忽略中间较短且接近的线段,从而快速找到最优解。

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

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.

这道题就是一个在第一象线有多个竖线,竖线长度就是高。两条竖线之间距离就是底。求最大面积。不过由于水桶原理,最大面积是由最短的竖线决定的。同时,我们还要考虑底。因为S=底*高。

方法是从两边开始查找,我们尽量要找两条竖线都很高,并且竖线之间距离很远的组合。所以对于中间低的竖线并且近的竖线可以不计算。每次计算完,更新max就可以了。

我写的原始版本:

class Solution {
public:
    int maxArea(vector<int>& height) {
        const int size = height.size();
        if(size < 2)
            return 0;
        int l = 0, r = size - 1;
        int res = 0;
        for(int i=0, j=size-1; i<j; ) {
            if(height[i] > height[l])
                l = i;
            if(height[j] > height[r])
                r = j;
            res = std::max(res, std::min(height[i], height[j]) * (r-l));
            if(height[i] < height[j])
                ++i;
            else
                --j;
        }
        return res;
    }
};

精简版本:

class Solution {
public:
    int maxArea(vector<int>& height) {
        int i = 0, j = height.size() - 1;
        int res = 0;
        while(i < j) {
            int h = std::min(height[i], height[j]);
            res = std::max(res, h * (j - i));
            while(height[i] <= h && i < j) ++i;
            while(height[j] <= h && i < j) --j;
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值