Problem
Givennnon-negative integersa1,a2, ...,an, where each represents a point at coordinate (i,ai).nvertical lines are drawn such that the two endpoints of lineiis 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 andnis at least 2.
找出两条线所形成的最大面积
暴力思路
- 两层for循环
- 时间复杂度: O(n ^ 2)
思路(Two Pointer)
- maintain a result variable, a left pointer and a right pointer
- update result
- if [left] < [right], left++
- else, right--
public int maxArea(int[] height) {
if (height == null || height.length == 0) return 0;
int l = 0;
int r = height.length - 1;
int res = 0;
while (l < r) {
res = Math.max(res, Math.min(height[l], height[r]) * (r - l));
if (height[l] < height[r]) {
l++;
} else {
r--;
}
}
return res;
}