classSolution{publicintmaxArea(int[] height){int n = height.length;int res =0, left =0, right = n -1;while(left < right){if(height[left]< height[right]){
res =Math.max(res,(right - left)* height[left]);
left++;}else{
res =Math.max(res,(right - left)* height[right]);
right--;}}return res;}}
双指针:left 指针和 right 指针,开始时 left 指针指向数组的开头,right 指针指向数组的结尾,即 left = 0,right = n - 1。
从两边向中间缩小,每次在缩小之前都要找到在两端的板子中较短的那一块,将其向中间缩小一格。
若缩小的是 left 和 right 指针指向的木板中较长的那一块,则只会使容器的蓄水量变小或不变。
当 left = 0,right = 8 时,res = 8,,若此时将 right 向左移动一位(长的),res = 7 变小了。
若缩小的是 left 和 right 指针指向的木板中较短的那一块,则容器的蓄水量会增大。
当 left = 0,right = 8 时,res = 8,,若此时将 left 向右移动一位(短的),res = 49 变大了。
蓄水量:res = Min(h[left], h[right]) * (right − left),由两端中较短的那一块木板来决定能够蓄水量(木桶原理)。