Container With Most Water水箱问题

这篇博客探讨了如何解决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.

这题就是要寻找到两个直线,中间的容积最大,容器的宽度就是下标 之差,高度取最短的那个直线:

对于ai,aj,其中i<j,求max (min(ai,aj))*(j-i)

看到题目第一下马上想到的就是暴力求解法:

<span style="font-size:14px;">class Solution {
public:
    int my_min(int a,int b)
    {
        return a<b?a:b;
    }
    int maxArea(vector<int>& height) {
        int L = height.size();
        int result = 0;
        for(int i =0;i<L-1;i++)
        {
            if(height[i]*(L-1-i)<=result)//剪枝
                continue;
            for(int j = i+1;j < L;j++)
            {
                result = (my_min(height[i],height[j])*(j-i))>result?(my_min(height[i],height[j])*(j-i)):result;
            }
        }
        return result;
    }
};
</span>
当然不用想也知道肯定超时。果然那句话:第一个想到的方法往往不是最好的方法。

这时换一个思路:

对于影响结果的几个因素,第一就是宽度,第二就是高度。暴力求解就是从宽度出发,假设只要宽度变宽都是有可能达到最优解的。但是现实中有这样这这样的可能,往后高度越来越小,但是这种情况下还是不能排除某些数据。

如果从高度来讲,最小的高度将影响结果,那我们每一次都调整最短的那个距离。

class Solution 
{
public:
    inline int my_min(int a,int b)
    {
        return a<b?a:b;
    }
    int maxArea(vector<int>& height)
    {
        int L = height.size();
        int head = 0;
        int rear = L-1;
        int result = 0;
       
        while(head < rear)
        {
             result = (my_min(height[head],height[rear])*(rear-head)>result)?(my_min(height[head],height[rear])*(rear-head)):result;
             if(height[head] <= height[rear])
             {
                 ++head;
             }
             else
             {
                 --rear;
             }
        }
        return result;
    }
};

提交运行成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值