題目描述:
https://leetcode-cn.com/problems/container-with-most-water/
給你 n 個非負整數 a1,a2,...,an,每個數代表座標中的一個點 (i, ai) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別爲 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。
說明:你不能傾斜容器,且 n 的值至少爲 2。
思路:
代碼實現:
class Solution {
public:
int maxArea(vector<int>& height) {
int l = 0, r = height.size()-1;
int area = 0;
while(l<r){
int res = min(height[l], height[r]) * (r - l);
area = max(area,res);
height[l] < height[r] ? ++l : --r;
}
return area;
}
};
優化:遇到重複的高度,跳過
class Solution {
public:
int maxArea(vector<int>& height) {
int l = 0, r = height.size()-1;
int area = 0;
while(l<r){
int h = min(height[l], height[r]);
int res = h * (r - l);
area = max(area,res);
while(l<r && h == height[l]) ++l;
while(l<r && h == height[r]) --r;
}
return area;
}
};