Description
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.
Solution
Two-pointer, time O(n), space O(1)
对于i和j来说,area的高度是由比较矮的那根柱子决定的。根据这个特性,可以使用two-pointer从一头一尾开始往中间扫,移动哪个pointer取决于移动谁潜在的area可能变大(反之如果潜在的area一定会变小,则不那么移动)。
显然每次应该移动较短的那一根,因为如果移动较长那根,area势必会变小。
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int maxArea = 0;
while (left < right) {
maxArea = Math.max(maxArea, (right - left)
* Math.min(height[left], height[right]));
if (height[left] < height[right]) {
++left;
} else {
--right;
}
}
return maxArea;
}
}