Leetcode-11 Container With Most Water

Container With Most Water

Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

Example 1

1
2
Input: [1,8,6,2,5,4,8,3,7]
Output: 49

解题思路

初始时刻让两壁分别位于两端,然后不断缩小两壁距离。为使容量有可能增大,须将矮的一端换成更高的壁。

复杂度分析

  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$

代码

1
2
3
4
5
6
7
8
9
10
11
12
int maxArea(vector<int>& height) {
int i = 0, j = height.size() - 1;
int area = (j - i)*min(height[i], height[j]);
int res = area;
while (i != j) {
if (height[i] < height[j])++i;
else --j;
area = (j - i)*min(height[i], height[j]);
if (area > res)res = area;
}
return res;
}