跳到主要内容

11. [✔][M]盛最多水的容器

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0)(i, height[i])

找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

返回容器可以储存的最大水量。

说明: 你不能倾斜容器。

示例 1:

img

输入:[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

提示:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104

题解:

接雨水问题

/*
* @lc app=leetcode.cn id=11 lang=typescript
*
* [11] 盛最多水的容器
*/

// @lc code=start
function maxArea(height: number[]): number {
let left = 0;
let right = height.length - 1;
let res = 0;
while (left < right) {
// 不断计算left和right之间的面积,取最大值
// 至于为什么height[left] <= height[right]时,left++,
// 是因为(right - left)是一定的,每次收缩都会减少1,但是面积是按照最低来的,所以下次再循环,肯定是把边长低的去掉
if (height[left] <= height[right]) {
res = Math.max(max, height[left] * (right - left));
left++;
} else {
res = Math.max(max, height[right] * (right - left));
right--;
}
}

return res;
};
// @lc code=end