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.
two pointer做出来了 但是solution简洁的多
public class Solution {
public int maxArea(int[] height) {
int maxarea = 0, l = 0, r = height.length - 1;
while (l < r) {
maxarea = Math.max(maxarea, Math.min(height[l], height[r]) * (r - l));
if (height[l] < height[r])
l++;
else
r--;
}
return maxarea;
}
}
想法是这样的 假如输入是 4,2,3,1,5
盛水量是由两边中较短的一边决定的 于是 我们首先初始化两边分变为数组的起始和结束
用maxarea存当前算出的最大面积 现在是4*(5-1) = 4
接下来 该将两边向中间移动了 但是移动那边呢
因为盛水量总是由高度低的一边决定 现在我们想最大化盛水量
如果右边向左移动 分两种情况
1.移动之后 右边高度大于左边 盛水量会减少 因为宽度变小 而高度是两边中较低的那个 也就是左边 没有变化
2.移动之后 右边小于左边 盛水量会减少 因为这次宽度和高度都变小了
也就是说 如果移动高度较高的一边 盛水量一定会减少 所以我们会尝试移动高度较低的一边
这样如果左边移动之后高度变高 才有可能去抵消因为宽度变所造成的盛水量减少
也可以这样想 我们每次求得都是以高度较低的一边为左边界 所形成的空间 的最大盛水量
最终把这些值求max 也就是最大area