题目:
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.
解答:
public class Solution {
public int maxArea(int[] height) {
int max = 0;
int left = 0, right = height.length - 1;
while (left < right) {
max = Math.max(max, (right - left) * Math.min(height[left], height[right]));
//这里如果左边的数比右边的数小,那么这就是取left这个位置时的面积最大值。因为不管right怎么向左移动,最大高度也还是height[left]的值,而宽只会减小。所以我们只有向右移动left才有可能遇到更大的height,从而有可能产生更大的面积。
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return max;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。