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.
思路:高度矮的是短板,从两端向中间搜索。
高的那一端向中间移动没有意义,因为计算面积的高不变(为矮的那端,或者高的那端变得比矮的那端更矮),而宽(j-i)却减少了,面积不可能增加。
因此,哪端矮就向中间搜索。
public class Solution {
public int maxArea(int[] height) {
int size = height.length;
int left = 0, right = size - 1;
int max = 0;
while (left < right) {
int minheight = height[left] < height[right] ? height[left] : height[right];
int tmp = minheight * (right - left);
max = max > tmp ? max : tmp;
if (height[left] < height[right])
left++;
else
right--;
}
return max;
}
}