11. 盛最多水的容器

192 阅读1分钟

题目

image.png

思路

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?
    • 只有缩小矮板子的指针,下一次的容量才有可能增大。

IMG_0103(20210401-004608).PNG

代码

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;
    }
}