LeetCode-11.盛最多水的容器

11. 盛最多水的容器

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

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

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

说明:你不能倾斜容器。

示例 1:

1
2
3
输入:[1,8,6,2,5,4,8,3,7]
输出:49
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例 2:

1
2
输入:height = [1,1]
输出:1

提示:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int maxArea(int[] height) {
int left=0;
int right=height.length-1;
int res=0;
while(left<right){
int current=Math.min(height[left],height[right])*(right-left);
res=Math.max(res,current);
if(height[left]<height[right]){
left++;
}
else{
right--;
}
}
return res;
}
}

LeetCode-11.盛最多水的容器
http://blog.hrseno.cn/2024/12/22/算法题-盛最多水的容器/
作者
黄浩森
发布于
2024年12月22日
许可协议