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.
这道题让求盛得最多的水有多少。一个桶,所能装的水取决于最短的板子。初始状态从第一个板和最后一个板开始算(1,n):
1、如果第一个板比最后一个板短,那么以第一个板为左板的情况,最大的装水量就是(1,n),接下来算(2,n)
2、如果第一个板比最后一个板长,那么以最后一个板为右板的情况,最大的装水量就是(1,n),接下来算(1,n-1)
3、重复2、3步
代码如下:
public class Solution {
public int maxArea(int[] height) {
int max = 0;
int left = 0, right = height.length - 1;
while (left < right) {
int contain = (right - left) * Math.min(height[left], height[right]);
if (contain > max) {
max = contain;
}
if(height[left] < height[right])
left ++;
else
right --;
}
return max;
}
}