Leetcode Algorithm 011. Container With Most Water
Container With Most Water
给定一系列不同高度,互相之间的间隔为1的板子,选取序列其中的两个板子,使其盛水量最多
解题思路
题目要求盛水量最多,实则位选取的两个板子的较短那个的高度与两个板子组成的矩形的面积最大。
一种简单的想法是去遍历所有的组合,复杂度为 O(n2) ,有没有更好的办法呢?
我们知道,假设我们选取了两块板
ai
和
aj
(其中
i<j
),短板的高度是
h
围成的面积是
所以,我们可以从外围开始搜索,根据以上原理掠过一些不合要求的挡板,逐渐把挡板的间隔缩短。
代码
#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