[leetcode]Container With Most Water

本文介绍了一种解决“寻找两条线段以构成容纳最多水量的容器”问题的方法。通过采用双指针技术,该算法从数组两端开始,并逐步向内移动指针,确保了高效地找出最优解。

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

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.

前天面试遇到的一道题,当着面试官的面没有做出来,我当时想着类似于84. Largest Rectangle in Histogram的解法,没想到是自己想太多。
这题是标准的双指针类问题,使用两个指针分别指向数组的头和尾向中间遍历(narrow down),每次只移动数值较小的指针,而且如果数值较小的指针向中间缩数值是递减的,则直接跳过。

int maxArea(vector<int>& height)
{
    int N = height.size();
    int i = 0, j = N - 1;
    int res = 0;
    while (i < j)
    {
        int lower = height[i] < height[j] ? i : j;
        res = max(res, height[lower] * (j - i));
        // make the lower bar as large as possible in next step
        // skip those decreasing numbers
        if (lower == i)
            for (i = i + 1; i < j && height[i] <= height[i - 1]; ++i);
        else
            for (j = j - 1; i < j && height[j] <= height[j + 1]; --j);
    }
    return res;
}

祝自己早日找到工作,干巴爹!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值