class Solution {
public int maxArea(int[] height) {
if (height == null || height.length < 2)
return 0;
int left = 0;
int right = height.length - 1;
int maxArea = 0;
while (left < right) {
int currentHeight = Math.min(height[left], height[right]);
int currentWidth = right - left;
maxArea = Math.max(maxArea, currentHeight * currentWidth);
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return maxArea;
}
}核心思路:分别从左右两边设置两个指针, 使用int currentHeight = Math.min(height[left], height[right]);比较左右两指针高度 ,使用 int currentWidth = right - left;获取到容器宽度,然后计算最大面积,一直移动较短边指针,直到两指针汇合。
为什么移动短边? 因为如果我们移动长边,无论新的高度是多少,容器的宽度
(right - left)一定会变小,而容器的高度受限于短板,不可能超过原来的短边,所以总面积必然减小或不变。只有尝试向内移动短边,才有可能遇到更高的板子,从而弥补宽度减小带来的损失,找到更大的面积。