给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。
说明:你不能倾斜容器。
输入:[1,8,6,2,5,4,8,3,7]
输出:49
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
输入:height = [1,1]
输出:1
public class Solution {
public int MaxArea(int[] height)
{
int res = 0;
for (int i = 0; i < height.Length; i++)
{
for (int j = i + 1; j < height.Length; j++)
{
int thisArea = (j - i) * Math.Min(height[i], height[j]);
res = Math.Max(res, thisArea);
}
}
return res;
}
}
public class Solution {
public int MaxArea(int[] height)
{
int res = 0;
int left = 0; int right = height.Length - 1;
while (left < right)
{
int thisArea = (right - left) * Math.Min(height[left], height[right]);
res = Math.Max(res, thisArea);
if (height[left] > height[right]) right--;
else left++;
}
return res;
}
}
public class Solution {
public int MaxArea(int[] height)
{
int res = 0;
int left = 0; int right = height.Length - 1;
while (left < right)
{
int minHeight = Math.Min(height[left], height[right]);
int thisArea = (right - left) * minHeight;
res = Math.Max(res, thisArea);
if (left < right && height[left] <= minHeight) left++;
if (left < right && height[right] <= minHeight) right--;
}
return res;
}
}
public class Solution {
public int maxArea(int[] height) {
int l = 0, r = height.length - 1;
int ans = 0;
while (l < r) {
int area = Math.min(height[l], height[r]) * (r - l);
ans = Math.max(ans, area);
if (height[l] <= height[r]) {
++l;
}
else {
--r;
}
}
return ans;
}
}
class Solution:
def maxArea(self, height: List[int]) -> int:
l, r = 0, len(height) - 1
ans = 0
while l < r:
area = min(height[l], height[r]) * (r - l)
ans = max(ans, area)
if height[l] <= height[r]:
l += 1
else:
r -= 1
return ans