示例 1:
输入:[1,8,6,2,5,4,8,3,7]
输出:49
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
示例 2:
输入:height = [1,1]
输出:1
示例 3:
输入:height = [4,3,2,1,4]
输出:16
示例 4:
输入:height = [1,2,1]
输出:2
提示:
n = height.length
2 <= n <= 3 * 104
0 <= height[i] <= 3 * 104
代码:
class Solution { public int maxArea(int[] height) { /** * 双指针解法 * 面积的计算:两个指针对应的索引差 * 两指针中的较小值 * 步进规则:面积计算结束,移动较小值的指针;左指针右移,右指针左移 * 结束条件:指针重叠时结束 */ int leftIndex = 0; int rightIndex = height.length - 1; int area = 0; //指针重叠时结束 while (leftIndex < rightIndex){ int leftValue = height[leftIndex]; int rightValue = height[rightIndex]; int tempValue; if (leftValue < rightValue){ //左边的值较小 tempValue = (rightIndex - leftIndex) * leftValue; leftIndex++; }else { //右边的值较小 tempValue = (rightIndex - leftIndex) * rightValue; rightIndex--; } area = area > tempValue ? area:tempValue; } return area; } }