题目
思路
The intuition behind this approach is that the area formed between the lines will always be limited by the height of the shorter line.
- 双指针解法
- 注意,只是选两端柱子作为容器,两个板子中间的不考虑
- 计算完当前max后,移动高度小的那个指针,why?
- 只有缩小矮板子的指针,下一次的容量才有可能增大。
代码
class Solution {
public int maxArea(int[] height) {
int i = 0, j = height.length - 1;
int max = 0;
while (i < j) {
//计算当前容量,更新最大容量
max = Math.max(max, Math.min(height[i], height[j]) * (j - i));
//移动指针,缩小矮板子的指针,下一次的容量才有可能增大
if (height[i] > height[j]) {
j--;
} else {
i++;
}
}
return max;
}
}