题目
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
储存水的面积受限于两个木板中较短的木板的高度,和两木板间的距离,所以我们可以从相距最远的两个木板开始,i指向最左边的木板,j指向最右边的木板,把每次得到的面积储存在max中,然后再移动两个木板中高度相对较小的木板 (i++或j --)
java 代码
public int maxArea(int[] height) {
int i = 0, j = height.length - 1;
int max = 0,area = 0;
while(i != j) {
if(height[i] < height[j]) {
area = height[i] * (j - i);
max = Math.max(area, max);
i++;
}else {
area = height[j] * (j - i);
max = Math.max(area, max);
j--;
}
}
return max;
}
最初,是想着从高度最大的开始,再用一个数组记录他们最初的位置。把这些木板安照从高到低的顺序排列,对应的位置也同时排序。