Container With Most Water

406 篇文章 0 订阅
406 篇文章 0 订阅

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.

Example:

  • Input: [1,8,6,2,5,4,8,3,7]
  • Output: 49

给定n个非负整数a1,a2,…,an,其中每个表示坐标(i,ai)处的点。 绘制n条垂直线,使得线i的两个端点位于(i,ai)和(i,0)。 找到两条线,它们与x轴一起形成一个容器,这样容器就含有最多的水。

注意:您可能不会倾斜容器,n至少为2。

2,题目思路

这道题的意思从题图可以很清楚的看出,就是求容器的最大容积,因为这道题是二维的,因此也是求矩形面积的最大值。

同时,因为是容器放水,所以还运用到了“木桶原理”,即容积取决于最短的那块木板。

因此,对于这个问题,我们可以从两端开始,向内依次遍历。先计算容积,然后找比当前最小高度更高的墙壁,作为可能的高度,并作为容积的计算。

3,代码实现

static auto speedup = [](){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return nullptr;
}();

class Solution {
public:
    int maxArea(vector<int>& height) {
        if(height.size() == 0)
            return 0;
        
        int totalWater = 0;
        int left = 0, right = height.size()-1;
        while(left < right){
            //水的容器以左右的最小值(木桶原理)
            int minH = min(height[left], height[right]);
            totalWater = max(totalWater, minH * (right - left));
            //从左往右找更高的木板(可能会让容量更大)
            while(height[left] <= minH && left < right)
                left++;
            //原因相同,从右往左找更高的木板
            while(height[right] <= minH && left < right)
                right--;
        }
        return totalWater;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值