11 盛最多水的容器

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。

找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

返回容器可以储存的最大水量。

说明:你不能倾斜容器。

输入:[1,8,6,2,5,4,8,3,7]
输出:49 
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例 2:

输入:height = [1,1]
输出:1

提示:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104
//剪枝
//第一层for:指向的i的高度 小于 其前的柱子的高度,则continue
class Solution {
public:
    int maxArea(vector<int>& height) {
        int max_pre_height=0;
        long max_capacity=0;
        long capacity;
        for(int i=0;i<height.size();i++){
            if(height[i]<=max_pre_height) continue;
            else{
                max_pre_height=height[i];
                for(int j=i+1;j<height.size();j++){
                    capacity=(j-i)*min(height[i],height[j]);
                    if(capacity>max_capacity) max_capacity=capacity;
                }
            }
        }
        return max_capacity;
    }
};

//O(n)
//双指针指向首尾两端
//指针每次向中间移动,(q-p)缩小即底变小
//此时如果寻求更大的面积则需要移动 指向更小高度柱子的指针
class Solution {
public:
    int maxArea(vector<int>& height) {
        int max_capacity=0;
        int temp;
        int p=0;
        int q=height.size()-1;
        while(p<q){
            temp=(q-p)*min(height[p],height[q]);
            if(temp>max_capacity) max_capacity=temp;
            if(height[p]<height[q]) p++;
            else q--;
        }
        return max_capacity;
    }
};
//双指针 再加剪枝
class Solution {
public:
    int maxArea(vector<int>& height) {
        int max_capacity=0;
        int max_r_height=0;
        int max_l_height=0;
        int temp;
        int p=0;
        int q=height.size()-1;
        while(p<q){
            if(height[p]<max_r_height){
                p++;
                continue;
            }
            if(height[q]<max_l_height){
                q--;
                continue;
            }
            max_r_height=height[p];
            max_l_height=height[q];

            temp=(q-p)*min(height[p],height[q]);
            if(temp>max_capacity) max_capacity=temp;
            if(height[p]<height[q]) {
                p++;
                }
            else {
                q--;
            }
        }
        return max_capacity;
    }
};

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值