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.
[分析] 用两个指针从两端往中间扫,计算两指针当前围成的矩形面积并更新全局最大值并移动高度矮的指针。方法2 做的小优化是扫描过程中,如果当前两指针中高度较矮的指针比之前的最矮指针小,则不需要计算所围成的矩形面积,因为宽和高都比之前小的情况下矩形面积必然更小。
此题思路和Trapping Rain Water的一种思路一致。
[分析] 用两个指针从两端往中间扫,计算两指针当前围成的矩形面积并更新全局最大值并移动高度矮的指针。方法2 做的小优化是扫描过程中,如果当前两指针中高度较矮的指针比之前的最矮指针小,则不需要计算所围成的矩形面积,因为宽和高都比之前小的情况下矩形面积必然更小。
此题思路和Trapping Rain Water的一种思路一致。
public class Solution {
public int maxArea(int[] height) {
if (height == null || height.length == 0)
return 0;
int l = 0, r = height.length - 1;
int minBar = 0, maxArea = 0;
while (l < r) {
int currMin = Math.min(height[l], height[r]);
if (currMin == height[l]) {
if (currMin > minBar)
maxArea = Math.max(maxArea, currMin * (r - l));
l++;
} else {
if (currMin > minBar)
maxArea = Math.max(maxArea, currMin * (r - l));
r--;
}
if (currMin > minBar)
minBar = currMin;
}
return maxArea;
}
public int maxArea1(int[] height) {
if (height == null || height.length == 0)
return 0;
int l = 0, r = height.length - 1;
int minBar = 0, maxArea = 0;
while (l < r) {
minBar = Math.min(height[l], height[r]);
if (minBar == height[l]) {
maxArea = Math.max(maxArea, minBar * (r - l));
l++;
} else {
maxArea = Math.max(maxArea, minBar * (r - l));
r--;
}
}
return maxArea;
}
}