# 盛最多水的容器

给你 n 个非负整数 a1,a2,...,an每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai)(i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器。

 

示例 1:

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

示例 3:

输入:height = [4,3,2,1,4]
输出:
16

示例 4:

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

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; int arr1[] = {1, 8, 6, 2, 5, 4, 8, 3, 7}; int length1 = sizeof(arr1) / sizeof(arr1[0]); vector nums1(arr1, arr1 + length1); cout << sol.maxArea(nums1) << endl; return 0; } ``` ## 答案 ```cpp class Solution { public: int maxArea(vector &height) { int res = 0; for (int i = 0; i < height.size(); i++) { for (int j = i + 1; j < height.size(); j++) { int temp1 = max(height[i], height[j]); int temp2 = temp1 * (j - i); res = min(res, temp2); } } return res; } }; ``` ## 选项 ### A ```cpp class Solution { public: int maxArea(vector &height) { int i = 0; int j = height.size() - 1; int res = 0; while (i < j) { int temp1 = min(height[i], height[j]); int temp2 = temp1 * (j - i); res = max(res, temp2); if (height[i] < height[j]) i++; else j--; } return res; } }; ``` ### B ```cpp class Solution { public: int maxArea(vector &height) { int tmp = 0, res = 0, max = 0; for (int i = 0; i < height.size(); ++i) { for (int j = i + 1; j < height.size(); ++j) { if (height[i] < height[j]) { tmp = height[i]; } else { tmp = height[j]; } res = tmp * (j - i); if (res > max) { max = res; } } } return max; } }; ``` ### C ```cpp class Solution { public: int maxArea(vector &height) { int tail = height.size() - 1; int head = 0; int maxarea = height.at(head) > height.at(tail) ? height.at(tail) * (tail - head) : height.at(head) * (tail - head); for (int i = 0; i < height.size(); i++) { if (maxarea < (height.at(head) > height.at(tail) ? height.at(tail) * (tail - head) : height.at(head) * (tail - head))) maxarea = height.at(head) > height.at(tail) ? height.at(tail) * (tail - head) : height.at(head) * (tail - head); if (height.at(head) > height.at(tail)) { tail--; } else { head++; } } return maxarea; } }; ```