

思路:
双重for循环列举出所有可能答案,找出其中的最大结果
class Solution {
public:
int maxArea(vector<int>& height)
{
int maxArea = 0;
for (int i = 0; i < height.size(); i++)
{
for (int j = 1; j < height.size(); j++)
maxArea = max(maxArea, (j - i) * min(height[i], height[j]));
}
return maxArea;
}
};
思路: 设置双指针 i,j 分别位于容器壁两端,根据规则移动指针(后续说明),并且更新面积最大值 res,直到 i == j 时返回 res。
指针移动规则:
每次选定围成水槽两板高度 h[i],h[j] 中的短板,向中间收窄 1 格。
复杂度分析:
图解:








代码:
class Solution {
public:
int maxArea(vector<int>& height)
{
int i = 0, j = height.size() - 1, res = 0;
while (i < j)
res = height[i] < height[j] ?
max(res, (j - i) * height[i++]) :
max(res, (j - i) * height[j--]);
return res;
}
};
\