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.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
给n个非负整数,每个代表一个坐标(i, ai)。把这些点画到一个二维坐标图里,然后把(i, ai)与(i, 0)相连形成线。找到两个线,使得之间能装最多的水。
提示:不能倾斜,n最少为2。
思路一,我们可以暴力的两层遍历,每一个条线与另外一条线能装多少水,记录最多的一个。时间复杂度为O(n2),空间复杂度为O(1)。
思路二,比较投巧,因为默认两条线的距离一样。我们从头和尾开始遍历,计算两条线能装多少水,然后比较头、尾大小,头小头++,否则尾--(为了防止出现头尾一样大的情况)。记录最大的空间。时间复杂度为O(n),空间复杂度为O(1)。
以下为代码:
public int maxArea(int[] height) {
int max = 0, l = 0, r = height.length - 1;
while (l < r) {
max = Math.max(max, Math.min(height[l], height[r]) * (r - l));
if(height[l] < height[r]) {
l++;
} else {
r--;
}
}
return max;
}