题目
代码(首刷自解)
因为矩形的高度是由 min(height[left], height[right]) 即较低的一边决定的。
你如果移动较低的那一边,那条边可能会变高,使得矩形的高度变大,进而就「有可能」使得矩形的面积变大;相反,如果你去移动较高的那一边,矩形的高度是无论如何都不会变大的,所以不可能使矩形的面积变得更大。
class Solution {
public:
int maxArea(vector<int>& height) {
int res = 0;
int left = 0, right = height.size() - 1;
while(left < right) {
res = max(min(height[left], height[right]) * (right-left), res);
if(height[left] < height[right])
left++;
else right--;
}
return res;
}
};
代码(8.30 二刷自解)
class Solution {
public:
int maxArea(vector<int>& height) {
int l = 0, r = height.size()-1;
int res = 0;
while(l < r) {
res = max(res, min(height[l], height[r])*(r-l));
if(height[l] < height[r])
l++;
else r--;
}
return res;
}
};
代码(9.16 三刷自解)
class Solution {
public:
int maxArea(vector<int>& height) {
int n = height.size();
int left = height[0], right = height[n-1];
int res = 0;
int i = 0, j = n-1;
while(i < j) {
left = max(left, height[i]);
right = max(right, height[j]);
res = max(res, (j-i)*min(left, right));
if(left < right) {
i++;
} else {
j--;
}
}
return res;
}
};