Leetcode Algorithm 011. Container With Most Water

Leetcode Algorithm 011. Container With Most Water

Container With Most Water
给定一系列不同高度,互相之间的间隔为1的板子,选取序列其中的两个板子,使其盛水量最多

解题思路

题目要求盛水量最多,实则位选取的两个板子的较短那个的高度与两个板子组成的矩形的面积最大。

一种简单的想法是去遍历所有的组合,复杂度为 O(n2) ,有没有更好的办法呢?

我们知道,假设我们选取了两块板 ai aj (其中 i<j ),短板的高度是 h 围成的面积是S=(ji)×h。对于板 ai aj (其中 ii<jj ),若它们之间的短板高度 hh 的话,必有 S=(ji)×hS

所以,我们可以从外围开始搜索,根据以上原理掠过一些不合要求的挡板,逐渐把挡板的间隔缩短。

代码

#include<iostream>
#include<vector>

using namespace std;

class Solution {
public:
    int maxArea(vector<int>& height) {
        int i = 0;
        int j = height.size() - 1;
        int area = 0;

        while (i < j) {
            int h = min(height[i], height[j]);
            area = max((j - i) * h, area);

            while (height[i] <= h && i < j)
                i++;
            while (height[j] <= h && i < j)
                j--;
        }

        return area;

    }
};

int main() {
    Solution s;

    int t;
    cin >> t;

    while (t--) {
        int n;
        cin >> n;

        vector<int> heights(n);

        for (int i = 0; i < n; i++) {
            cin >> heights[i];
        }

        cout << s.maxArea(heights) << endl;

    }

    return 0;
}

测试样例

第一行是样例的数目t,每组样例占两行,第一行是挡板的数目n,第二列是n个挡板的高度。

4
2
1 1
10
1 2 3 4 5 5 4 3 2 1
5
5 4 1 2 5
8
1 4 2 6 8 2 0 2

输出

1
15
20
12
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值